honkster-acts_as_solr 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (154) hide show
  1. data/CHANGE_LOG +233 -0
  2. data/LICENSE +19 -0
  3. data/README.markdown +118 -0
  4. data/README.rdoc +107 -0
  5. data/Rakefile +68 -0
  6. data/TESTING_THE_PLUGIN +25 -0
  7. data/VERSION +1 -0
  8. data/lib/acts_as_solr/acts_methods.rb +279 -0
  9. data/lib/acts_as_solr/class_methods.rb +236 -0
  10. data/lib/acts_as_solr/common_methods.rb +89 -0
  11. data/lib/acts_as_solr/deprecation.rb +61 -0
  12. data/lib/acts_as_solr/instance_methods.rb +166 -0
  13. data/lib/acts_as_solr/lazy_document.rb +18 -0
  14. data/lib/acts_as_solr/parser_methods.rb +201 -0
  15. data/lib/acts_as_solr/search_results.rb +68 -0
  16. data/lib/acts_as_solr/solr_fixtures.rb +13 -0
  17. data/lib/acts_as_solr/tasks/database.rake +16 -0
  18. data/lib/acts_as_solr/tasks/solr.rake +132 -0
  19. data/lib/acts_as_solr/tasks/test.rake +5 -0
  20. data/lib/acts_as_solr/tasks.rb +10 -0
  21. data/lib/acts_as_solr.rb +64 -0
  22. data/lib/solr/connection.rb +177 -0
  23. data/lib/solr/document.rb +75 -0
  24. data/lib/solr/exception.rb +13 -0
  25. data/lib/solr/field.rb +36 -0
  26. data/lib/solr/importer/array_mapper.rb +26 -0
  27. data/lib/solr/importer/delimited_file_source.rb +38 -0
  28. data/lib/solr/importer/hpricot_mapper.rb +27 -0
  29. data/lib/solr/importer/mapper.rb +51 -0
  30. data/lib/solr/importer/solr_source.rb +41 -0
  31. data/lib/solr/importer/xpath_mapper.rb +35 -0
  32. data/lib/solr/importer.rb +19 -0
  33. data/lib/solr/indexer.rb +52 -0
  34. data/lib/solr/request/add_document.rb +58 -0
  35. data/lib/solr/request/base.rb +36 -0
  36. data/lib/solr/request/commit.rb +29 -0
  37. data/lib/solr/request/delete.rb +48 -0
  38. data/lib/solr/request/dismax.rb +46 -0
  39. data/lib/solr/request/index_info.rb +22 -0
  40. data/lib/solr/request/modify_document.rb +46 -0
  41. data/lib/solr/request/optimize.rb +19 -0
  42. data/lib/solr/request/ping.rb +36 -0
  43. data/lib/solr/request/select.rb +54 -0
  44. data/lib/solr/request/spellcheck.rb +30 -0
  45. data/lib/solr/request/standard.rb +402 -0
  46. data/lib/solr/request/update.rb +23 -0
  47. data/lib/solr/request.rb +26 -0
  48. data/lib/solr/response/add_document.rb +17 -0
  49. data/lib/solr/response/base.rb +42 -0
  50. data/lib/solr/response/commit.rb +15 -0
  51. data/lib/solr/response/delete.rb +13 -0
  52. data/lib/solr/response/dismax.rb +8 -0
  53. data/lib/solr/response/index_info.rb +26 -0
  54. data/lib/solr/response/modify_document.rb +17 -0
  55. data/lib/solr/response/optimize.rb +14 -0
  56. data/lib/solr/response/ping.rb +26 -0
  57. data/lib/solr/response/ruby.rb +42 -0
  58. data/lib/solr/response/select.rb +17 -0
  59. data/lib/solr/response/spellcheck.rb +20 -0
  60. data/lib/solr/response/standard.rb +60 -0
  61. data/lib/solr/response/xml.rb +39 -0
  62. data/lib/solr/response.rb +27 -0
  63. data/lib/solr/solrtasks.rb +27 -0
  64. data/lib/solr/util.rb +32 -0
  65. data/lib/solr/xml.rb +44 -0
  66. data/lib/solr.rb +26 -0
  67. data/solr/CHANGES.txt +1207 -0
  68. data/solr/LICENSE.txt +712 -0
  69. data/solr/NOTICE.txt +90 -0
  70. data/solr/etc/jetty.xml +205 -0
  71. data/solr/etc/webdefault.xml +379 -0
  72. data/solr/lib/easymock.jar +0 -0
  73. data/solr/lib/jetty-6.1.3.jar +0 -0
  74. data/solr/lib/jetty-util-6.1.3.jar +0 -0
  75. data/solr/lib/jsp-2.1/ant-1.6.5.jar +0 -0
  76. data/solr/lib/jsp-2.1/core-3.1.1.jar +0 -0
  77. data/solr/lib/jsp-2.1/jsp-2.1.jar +0 -0
  78. data/solr/lib/jsp-2.1/jsp-api-2.1.jar +0 -0
  79. data/solr/lib/servlet-api-2.4.jar +0 -0
  80. data/solr/lib/servlet-api-2.5-6.1.3.jar +0 -0
  81. data/solr/lib/xpp3-1.1.3.4.O.jar +0 -0
  82. data/solr/solr/README.txt +52 -0
  83. data/solr/solr/bin/abc +176 -0
  84. data/solr/solr/bin/abo +176 -0
  85. data/solr/solr/bin/backup +108 -0
  86. data/solr/solr/bin/backupcleaner +142 -0
  87. data/solr/solr/bin/commit +128 -0
  88. data/solr/solr/bin/optimize +129 -0
  89. data/solr/solr/bin/readercycle +129 -0
  90. data/solr/solr/bin/rsyncd-disable +77 -0
  91. data/solr/solr/bin/rsyncd-enable +76 -0
  92. data/solr/solr/bin/rsyncd-start +145 -0
  93. data/solr/solr/bin/rsyncd-stop +105 -0
  94. data/solr/solr/bin/scripts-util +83 -0
  95. data/solr/solr/bin/snapcleaner +148 -0
  96. data/solr/solr/bin/snapinstaller +168 -0
  97. data/solr/solr/bin/snappuller +248 -0
  98. data/solr/solr/bin/snappuller-disable +77 -0
  99. data/solr/solr/bin/snappuller-enable +77 -0
  100. data/solr/solr/bin/snapshooter +109 -0
  101. data/solr/solr/conf/admin-extra.html +31 -0
  102. data/solr/solr/conf/protwords.txt +21 -0
  103. data/solr/solr/conf/schema.xml +126 -0
  104. data/solr/solr/conf/scripts.conf +24 -0
  105. data/solr/solr/conf/solrconfig.xml +458 -0
  106. data/solr/solr/conf/stopwords.txt +57 -0
  107. data/solr/solr/conf/synonyms.txt +31 -0
  108. data/solr/solr/conf/xslt/example.xsl +132 -0
  109. data/solr/solr/conf/xslt/example_atom.xsl +63 -0
  110. data/solr/solr/conf/xslt/example_rss.xsl +62 -0
  111. data/solr/start.jar +0 -0
  112. data/solr/webapps/solr.war +0 -0
  113. data/test/config/solr.yml +2 -0
  114. data/test/db/connections/mysql/connection.rb +10 -0
  115. data/test/db/connections/sqlite/connection.rb +8 -0
  116. data/test/db/migrate/001_create_books.rb +15 -0
  117. data/test/db/migrate/002_create_movies.rb +12 -0
  118. data/test/db/migrate/003_create_categories.rb +11 -0
  119. data/test/db/migrate/004_create_electronics.rb +16 -0
  120. data/test/db/migrate/005_create_authors.rb +12 -0
  121. data/test/db/migrate/006_create_postings.rb +9 -0
  122. data/test/db/migrate/007_create_posts.rb +13 -0
  123. data/test/db/migrate/008_create_gadgets.rb +11 -0
  124. data/test/fixtures/authors.yml +9 -0
  125. data/test/fixtures/books.yml +13 -0
  126. data/test/fixtures/categories.yml +7 -0
  127. data/test/fixtures/db_definitions/mysql.sql +41 -0
  128. data/test/fixtures/electronics.yml +49 -0
  129. data/test/fixtures/movies.yml +9 -0
  130. data/test/fixtures/postings.yml +10 -0
  131. data/test/functional/acts_as_solr_test.rb +413 -0
  132. data/test/functional/association_indexing_test.rb +37 -0
  133. data/test/functional/faceted_search_test.rb +163 -0
  134. data/test/functional/multi_solr_search_test.rb +51 -0
  135. data/test/models/author.rb +10 -0
  136. data/test/models/book.rb +10 -0
  137. data/test/models/category.rb +8 -0
  138. data/test/models/electronic.rb +21 -0
  139. data/test/models/gadget.rb +9 -0
  140. data/test/models/movie.rb +17 -0
  141. data/test/models/novel.rb +2 -0
  142. data/test/models/post.rb +3 -0
  143. data/test/models/posting.rb +11 -0
  144. data/test/test_helper.rb +51 -0
  145. data/test/unit/acts_methods_shoulda.rb +68 -0
  146. data/test/unit/class_methods_shoulda.rb +85 -0
  147. data/test/unit/common_methods_shoulda.rb +111 -0
  148. data/test/unit/instance_methods_shoulda.rb +318 -0
  149. data/test/unit/lazy_document_shoulda.rb +34 -0
  150. data/test/unit/parser_instance.rb +19 -0
  151. data/test/unit/parser_methods_shoulda.rb +268 -0
  152. data/test/unit/solr_instance.rb +44 -0
  153. data/test/unit/test_helper.rb +22 -0
  154. metadata +239 -0
@@ -0,0 +1,68 @@
1
+ module ActsAsSolr #:nodoc:
2
+
3
+ # TODO: Possibly looking into hooking it up with Solr::Response::Standard
4
+ #
5
+ # Class that returns the search results with four methods.
6
+ #
7
+ # books = Book.find_by_solr 'ruby'
8
+ #
9
+ # the above will return a SearchResults class with 4 methods:
10
+ #
11
+ # docs|results|records: will return an array of records found
12
+ #
13
+ # books.records.empty?
14
+ # => false
15
+ #
16
+ # total|num_found|total_hits: will return the total number of records found
17
+ #
18
+ # books.total
19
+ # => 2
20
+ #
21
+ # facets: will return the facets when doing a faceted search
22
+ #
23
+ # max_score|highest_score: returns the highest score found
24
+ #
25
+ # books.max_score
26
+ # => 1.3213213
27
+ #
28
+ #
29
+ class SearchResults
30
+ def initialize(solr_data={})
31
+ @solr_data = solr_data
32
+ end
33
+
34
+ # Returns an array with the instances. This method
35
+ # is also aliased as docs and records
36
+ def results
37
+ @solr_data[:docs]
38
+ end
39
+
40
+ # Returns the total records found. This method is
41
+ # also aliased as num_found and total_hits
42
+ def total
43
+ @solr_data[:total]
44
+ end
45
+
46
+ # Returns the facets when doing a faceted search
47
+ def facets
48
+ @solr_data[:facets]
49
+ end
50
+
51
+ # Returns the highest score found. This method is
52
+ # also aliased as highest_score
53
+ def max_score
54
+ @solr_data[:max_score]
55
+ end
56
+
57
+ def query_time
58
+ @solr_data[:query_time]
59
+ end
60
+
61
+ alias docs results
62
+ alias records results
63
+ alias num_found total
64
+ alias total_hits total
65
+ alias highest_score max_score
66
+ end
67
+
68
+ end
@@ -0,0 +1,13 @@
1
+ module ActsAsSolr
2
+
3
+ class SolrFixtures
4
+ def self.load(table_names)
5
+ [table_names].flatten.map { |n| n.to_s }.each do |table_name|
6
+ klass = instance_eval(File.split(table_name.to_s).last.to_s.gsub('_',' ').split(" ").collect{|w| w.capitalize}.to_s.singularize)
7
+ klass.rebuild_solr_index if klass.respond_to?(:rebuild_solr_index)
8
+ end
9
+ ActsAsSolr::Post.execute(Solr::Request::Commit.new)
10
+ end
11
+ end
12
+
13
+ end
@@ -0,0 +1,16 @@
1
+ namespace :db do
2
+ namespace :fixtures do
3
+ desc "Load fixtures into the current environment's database. Load specific fixtures using FIXTURES=x,y"
4
+ task :load => :environment do
5
+ begin
6
+ ActsAsSolr::Post.execute(Solr::Request::Delete.new(:query => "*:*"))
7
+ ActsAsSolr::Post.execute(Solr::Request::Commit.new)
8
+ (ENV['FIXTURES'] ? ENV['FIXTURES'].split(/,/) : Dir.glob(File.join(RAILS_ROOT, 'test', 'fixtures', '*.{yml,csv}'))).each do |fixture_file|
9
+ ActsAsSolr::SolrFixtures.load(File.basename(fixture_file, '.*'))
10
+ end
11
+ puts "The fixtures loaded have been added to Solr"
12
+ rescue
13
+ end
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,132 @@
1
+ namespace :solr do
2
+
3
+ desc 'Starts Solr. Options accepted: RAILS_ENV=your_env, PORT=XX. Defaults to development if none.'
4
+ task :start do
5
+ require File.expand_path("#{File.dirname(__FILE__)}/../../config/solr_environment")
6
+ begin
7
+ n = Net::HTTP.new('127.0.0.1', SOLR_PORT)
8
+ n.request_head('/').value
9
+
10
+ rescue Net::HTTPServerException #responding
11
+ puts "Port #{SOLR_PORT} in use" and return
12
+
13
+ rescue Errno::ECONNREFUSED #not responding
14
+ Dir.chdir(SOLR_PATH) do
15
+ pid = fork do
16
+ #STDERR.close
17
+ exec "java #{SOLR_JVM_OPTIONS} -Dsolr.data.dir=#{SOLR_DATA_PATH} -Djetty.logs=#{SOLR_LOGS_PATH} -Djetty.port=#{SOLR_PORT} -jar start.jar"
18
+ end
19
+ sleep(5)
20
+ File.open("#{SOLR_PIDS_PATH}/#{ENV['RAILS_ENV']}_pid", "w"){ |f| f << pid}
21
+ puts "#{ENV['RAILS_ENV']} Solr started successfully on #{SOLR_PORT}, pid: #{pid}."
22
+ end
23
+ end
24
+ end
25
+
26
+ desc 'Stops Solr. Specify the environment by using: RAILS_ENV=your_env. Defaults to development if none.'
27
+ task :stop do
28
+ require File.expand_path("#{File.dirname(__FILE__)}/../../config/solr_environment")
29
+ fork do
30
+ file_path = "#{SOLR_PIDS_PATH}/#{ENV['RAILS_ENV']}_pid"
31
+ if File.exists?(file_path)
32
+ File.open(file_path, "r") do |f|
33
+ pid = f.readline
34
+ Process.kill('TERM', pid.to_i)
35
+ end
36
+ File.unlink(file_path)
37
+ Rake::Task["solr:destroy_index"].invoke if ENV['RAILS_ENV'] == 'test'
38
+ puts "Solr shutdown successfully."
39
+ else
40
+ puts "PID file not found at #{file_path}. Either Solr is not running or no PID file was written."
41
+ end
42
+ end
43
+ end
44
+
45
+ desc 'Remove Solr index'
46
+ task :destroy_index do
47
+ require File.expand_path("#{File.dirname(__FILE__)}/../../config/solr_environment")
48
+ raise "In production mode. I'm not going to delete the index, sorry." if ENV['RAILS_ENV'] == "production"
49
+ if File.exists?("#{SOLR_DATA_PATH}")
50
+ Dir["#{SOLR_DATA_PATH}/index/*"].each{|f| File.unlink(f)}
51
+ Dir.rmdir("#{SOLR_DATA_PATH}/index")
52
+ puts "Index files removed under " + ENV['RAILS_ENV'] + " environment"
53
+ end
54
+ end
55
+
56
+ # this task is by Henrik Nyh
57
+ # http://henrik.nyh.se/2007/06/rake-task-to-reindex-models-for-acts_as_solr
58
+ desc %{Reindexes data for all acts_as_solr models. Clears index first to get rid of orphaned records and optimizes index afterwards. RAILS_ENV=your_env to set environment. ONLY=book,person,magazine to only reindex those models; EXCEPT=book,magazine to exclude those models. START_SERVER=true to solr:start before and solr:stop after. BATCH=123 to post/commit in batches of that size: default is 300. CLEAR=false to not clear the index first; OPTIMIZE=false to not optimize the index afterwards.}
59
+ task :reindex => :environment do
60
+ require File.expand_path("#{File.dirname(__FILE__)}/../../config/solr_environment")
61
+
62
+ includes = env_array_to_constants('ONLY')
63
+ if includes.empty?
64
+ includes = Dir.glob("#{RAILS_ROOT}/app/models/*.rb").map { |path| File.basename(path, ".rb").camelize.constantize }
65
+ end
66
+ excludes = env_array_to_constants('EXCEPT')
67
+ includes -= excludes
68
+
69
+ optimize = env_to_bool('OPTIMIZE', true)
70
+ start_server = env_to_bool('START_SERVER', false)
71
+ clear_first = env_to_bool('CLEAR', true)
72
+ batch_size = ENV['BATCH'].to_i.nonzero? || 300
73
+ debug_output = env_to_bool("DEBUG", false)
74
+
75
+ RAILS_DEFAULT_LOGGER.level = ActiveSupport::BufferedLogger::INFO unless debug_output
76
+
77
+ if start_server
78
+ puts "Starting Solr server..."
79
+ Rake::Task["solr:start"].invoke
80
+ end
81
+
82
+ # Disable solr_optimize
83
+ module ActsAsSolr::CommonMethods
84
+ def blank() end
85
+ alias_method :deferred_solr_optimize, :solr_optimize
86
+ alias_method :solr_optimize, :blank
87
+ end
88
+
89
+ models = includes.select { |m| m.respond_to?(:rebuild_solr_index) }
90
+ models.each do |model|
91
+
92
+ if clear_first
93
+ puts "Clearing index for #{model}..."
94
+ ActsAsSolr::Post.execute(Solr::Request::Delete.new(:query => "#{model.solr_configuration[:type_field]}:#{model}"))
95
+ ActsAsSolr::Post.execute(Solr::Request::Commit.new)
96
+ end
97
+
98
+ puts "Rebuilding index for #{model}..."
99
+ model.rebuild_solr_index(batch_size)
100
+
101
+ end
102
+
103
+ if models.empty?
104
+ puts "There were no models to reindex."
105
+ elsif optimize
106
+ puts "Optimizing..."
107
+ models.last.deferred_solr_optimize
108
+ end
109
+
110
+ if start_server
111
+ puts "Shutting down Solr server..."
112
+ Rake::Task["solr:stop"].invoke
113
+ end
114
+
115
+ end
116
+
117
+ def env_array_to_constants(env)
118
+ env = ENV[env] || ''
119
+ env.split(/\s*,\s*/).map { |m| m.singularize.camelize.constantize }.uniq
120
+ end
121
+
122
+ def env_to_bool(env, default)
123
+ env = ENV[env] || ''
124
+ case env
125
+ when /^true$/i then true
126
+ when /^false$/i then false
127
+ else default
128
+ end
129
+ end
130
+
131
+ end
132
+
@@ -0,0 +1,5 @@
1
+ namespace :test do
2
+ task :migrate do
3
+ ActiveRecord::Migrator.migrate("test/db/migrate/", ENV["VERSION"] ? ENV["VERSION"].to_i : nil)
4
+ end
5
+ end
@@ -0,0 +1,10 @@
1
+ dir = File.dirname(__FILE__)
2
+ require 'rubygems'
3
+ require 'rake'
4
+ require 'net/http'
5
+ require 'active_record'
6
+ require File.expand_path("#{dir}/solr_fixtures")
7
+
8
+ load File.expand_path("#{dir}/tasks/database.rake")
9
+ load File.expand_path("#{dir}/tasks/solr.rake")
10
+ load File.expand_path("#{dir}/tasks/test.rake")
@@ -0,0 +1,64 @@
1
+ # Copyright (c) 2006 Erik Hatcher, Thiago Jackiw
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ # of this software and associated documentation files (the "Software"), to deal
5
+ # in the Software without restriction, including without limitation the rights
6
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ # copies of the Software, and to permit persons to whom the Software is
8
+ # furnished to do so, subject to the following conditions:
9
+ #
10
+ # The above copyright notice and this permission notice shall be included in all
11
+ # copies or substantial portions of the Software.
12
+ #
13
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ # SOFTWARE.
20
+
21
+ require 'active_record'
22
+ require 'rexml/document'
23
+ require 'net/http'
24
+ require 'yaml'
25
+ require 'time'
26
+ require 'erb'
27
+ require 'rexml/xpath'
28
+
29
+ require File.dirname(__FILE__) + '/solr'
30
+ require File.dirname(__FILE__) + '/acts_as_solr/acts_methods'
31
+ require File.dirname(__FILE__) + '/acts_as_solr/common_methods'
32
+ require File.dirname(__FILE__) + '/acts_as_solr/parser_methods'
33
+ require File.dirname(__FILE__) + '/acts_as_solr/class_methods'
34
+ require File.dirname(__FILE__) + '/acts_as_solr/instance_methods'
35
+ require File.dirname(__FILE__) + '/acts_as_solr/common_methods'
36
+ require File.dirname(__FILE__) + '/acts_as_solr/deprecation'
37
+ require File.dirname(__FILE__) + '/acts_as_solr/search_results'
38
+ require File.dirname(__FILE__) + '/acts_as_solr/lazy_document'
39
+ module ActsAsSolr
40
+
41
+ class Post
42
+ def self.execute(request)
43
+ begin
44
+ if File.exists?(RAILS_ROOT+'/config/solr.yml')
45
+ config = YAML::load_file(RAILS_ROOT+'/config/solr.yml')
46
+ url = config[RAILS_ENV]['url']
47
+ # for backwards compatibility
48
+ url ||= "http://#{config[RAILS_ENV]['host']}:#{config[RAILS_ENV]['port']}/#{config[RAILS_ENV]['servlet_path']}"
49
+ else
50
+ url = 'http://localhost:8982/solr'
51
+ end
52
+ connection = Solr::Connection.new(url)
53
+ return connection.send(request)
54
+ rescue
55
+ raise "Couldn't connect to the Solr server at #{url}. #{$!}"
56
+ false
57
+ end
58
+ end
59
+ end
60
+
61
+ end
62
+
63
+ # reopen ActiveRecord and include the acts_as_solr method
64
+ ActiveRecord::Base.extend ActsAsSolr::ActsMethods
@@ -0,0 +1,177 @@
1
+ # The ASF licenses this file to You under the Apache License, Version 2.0
2
+ # (the "License"); you may not use this file except in compliance with
3
+ # the License. You may obtain a copy of the License at
4
+ #
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ #
7
+ # Unless required by applicable law or agreed to in writing, software
8
+ # distributed under the License is distributed on an "AS IS" BASIS,
9
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+ # See the License for the specific language governing permissions and
11
+ # limitations under the License.
12
+
13
+ # TODO: add a convenience method to POST a Solr .xml file, like Solr's example post.sh
14
+
15
+ class Solr::Connection
16
+ attr_reader :url, :autocommit, :connection
17
+
18
+ # create a connection to a solr instance using the url for the solr
19
+ # application context:
20
+ #
21
+ # conn = Solr::Connection.new("http://example.com:8080/solr")
22
+ #
23
+ # if you would prefer to have all adds/updates autocommitted,
24
+ # use :autocommit => :on
25
+ #
26
+ # conn = Solr::Connection.new('http://example.com:8080/solr',
27
+ # :autocommit => :on)
28
+
29
+ def initialize(url="http://localhost:8983/solr", opts={})
30
+ @url = URI.parse(url)
31
+ unless @url.kind_of? URI::HTTP
32
+ raise "invalid http url: #{url}"
33
+ end
34
+
35
+ # TODO: Autocommit seems nice at one level, but it currently is confusing because
36
+ # only calls to Connection#add/#update/#delete, though a Connection#send(AddDocument.new(...))
37
+ # does not autocommit. Maybe #send should check for the request types that require a commit and
38
+ # commit in #send instead of the individual methods?
39
+ @autocommit = opts[:autocommit] == :on
40
+
41
+ # Not actually opening the connection yet, just setting up the persistent connection.
42
+ @connection = Net::HTTP.new(@url.host, @url.port)
43
+
44
+ @connection.read_timeout = opts[:timeout] if opts[:timeout]
45
+ end
46
+
47
+ # add a document to the index. you can pass in either a hash
48
+ #
49
+ # conn.add(:id => 123, :title => 'Tlon, Uqbar, Orbis Tertius')
50
+ #
51
+ # or a Solr::Document
52
+ #
53
+ # conn.add(Solr::Document.new(:id => 123, :title = 'On Writing')
54
+ #
55
+ # true/false will be returned to designate success/failure
56
+
57
+ def add(doc)
58
+ request = Solr::Request::AddDocument.new(doc)
59
+ response = send(request)
60
+ commit if @autocommit
61
+ return response.ok?
62
+ end
63
+
64
+ # update a document in the index (really just an alias to add)
65
+
66
+ def update(doc)
67
+ return add(doc)
68
+ end
69
+
70
+ # performs a standard query and returns a Solr::Response::Standard
71
+ #
72
+ # response = conn.query('borges')
73
+ #
74
+ # alternative you can pass in a block and iterate over hits
75
+ #
76
+ # conn.query('borges') do |hit|
77
+ # puts hit
78
+ # end
79
+ #
80
+ # options include:
81
+ #
82
+ # :sort, :default_field, :rows, :filter_queries, :debug_query,
83
+ # :explain_other, :facets, :highlighting, :mlt,
84
+ # :operator => :or / :and
85
+ # :start => defaults to 0
86
+ # :field_list => array, defaults to ["*", "score"]
87
+
88
+ def query(query, options={}, &action)
89
+ # TODO: Shouldn't this return an exception if the Solr status is not ok? (rather than true/false).
90
+ create_and_send_query(Solr::Request::Standard, options.update(:query => query), &action)
91
+ end
92
+
93
+ # performs a dismax search and returns a Solr::Response::Standard
94
+ #
95
+ # response = conn.search('borges')
96
+ #
97
+ # options are same as query, but also include:
98
+ #
99
+ # :tie_breaker, :query_fields, :minimum_match, :phrase_fields,
100
+ # :phrase_slop, :boost_query, :boost_functions
101
+
102
+ def search(query, options={}, &action)
103
+ create_and_send_query(Solr::Request::Dismax, options.update(:query => query), &action)
104
+ end
105
+
106
+ # sends a commit message to the server
107
+ def commit(options={})
108
+ response = send(Solr::Request::Commit.new(options))
109
+ return response.ok?
110
+ end
111
+
112
+ # sends an optimize message to the server
113
+ def optimize
114
+ response = send(Solr::Request::Optimize.new)
115
+ return response.ok?
116
+ end
117
+
118
+ # pings the connection and returns true/false if it is alive or not
119
+ def ping
120
+ begin
121
+ response = send(Solr::Request::Ping.new)
122
+ return response.ok?
123
+ rescue
124
+ return false
125
+ end
126
+ end
127
+
128
+ # delete a document from the index using the document id
129
+ def delete(document_id)
130
+ response = send(Solr::Request::Delete.new(:id => document_id))
131
+ commit if @autocommit
132
+ response.ok?
133
+ end
134
+
135
+ # delete using a query
136
+ def delete_by_query(query)
137
+ response = send(Solr::Request::Delete.new(:query => query))
138
+ commit if @autocommit
139
+ response.ok?
140
+ end
141
+
142
+ def info
143
+ send(Solr::Request::IndexInfo.new)
144
+ end
145
+
146
+ # send a given Solr::Request and return a RubyResponse or XmlResponse
147
+ # depending on the type of request
148
+ def send(request)
149
+ data = post(request)
150
+ Solr::Response::Base.make_response(request, data)
151
+ end
152
+
153
+ # send the http post request to solr; for convenience there are shortcuts
154
+ # to some requests: add(), query(), commit(), delete() or send()
155
+ def post(request)
156
+ response = @connection.post(@url.path + "/" + request.handler,
157
+ request.to_s,
158
+ { "Content-Type" => request.content_type })
159
+
160
+ case response
161
+ when Net::HTTPSuccess then response.body
162
+ else
163
+ response.error!
164
+ end
165
+
166
+ end
167
+
168
+ private
169
+
170
+ def create_and_send_query(klass, options = {}, &action)
171
+ request = klass.new(options)
172
+ response = send(request)
173
+ return response unless action
174
+ response.each {|hit| action.call(hit)}
175
+ end
176
+
177
+ end