Using Solr From Ruby

Solr has an optional Ruby response format that extends the JSON output to allow the response to be safely eval’d by Ruby’s interpreter

This Ruby response format differs from JSON in the following ways:

  • Ruby’s single quoted strings are used to prevent possible string exploits

    • \ and ' are the only two characters escaped…​

    • unicode escapes not used…​ data is written as raw UTF-8

  • nil used for null

  • => used as the key/value separator in maps

Here’s an example Ruby response from Solr, for a request like http://localhost:8983/solr/techproducts/select?q=iPod&wt=ruby&indent=on (with Solr launching using bin/solr start -e techproducts):

        'name'=>'iPod & iPod Mini USB 2.0 Cable',
        'features'=>['car power adapter for iPod, white'],
        'name'=>'Belkin Mobile Power Cord for iPod w/ Dock',
        'features'=>['car power adapter, white'],
        'name'=>'Apple 60 GB iPod with Video Playback Black',
        'manu'=>'Apple Computer Inc.',
        'features'=>['iTunes, Podcasts, Audiobooks',
          'Stores up to 15,000 songs, 25,000 photos, or 150 hours of video',
          '2.5-inch, 320x240 color TFT LCD display with LED backlight',
          'Up to 20 hours of battery life',
          'Plays AAC, MP3, WAV, AIFF, Audible, Apple Lossless, H.264 video',
          'Notes, Calendar, Phone book, Hold button, Date display, Photo wallet, Built-in games, JPEG photo playback, Upgradeable firmware, USB 2.0 compatibility, Playback speed control, Rechargeable capability, Battery level indication'],
        'includes'=>'earbud headphones, USB cable',

Here is a simple example of how one may query Solr using the Ruby response format:

require 'net/http'

h ='localhost', 8983)
http_response = h.get('/solr/techproducts/select?q=iPod&wt=ruby')
rsp = eval(http_response.body)

puts 'number of matches = ' + rsp['response']['numFound'].to_s
#print out the name field for each returned document
rsp['response']['docs'].each { |doc| puts 'name field = ' + doc['name'] }

For simple interactions with Solr, this may be all you need! If you are building complex interactions with Solr, then consider the libraries mentioned at

Comments on this Page

We welcome feedback on Solr documentation. However, we cannot provide application support via comments. If you need help, please send a message to the Solr User mailing list.