acts_as_solr_reloaded 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (197) hide show
  1. data/LICENSE +22 -0
  2. data/README.markdown +64 -0
  3. data/README.rdoc +93 -0
  4. data/Rakefile +71 -0
  5. data/TESTING_THE_PLUGIN +25 -0
  6. data/VERSION +1 -0
  7. data/config/solr.yml +14 -0
  8. data/config/solr_environment.rb +35 -0
  9. data/generators/dynamic_attributes_migration/dynamic_attributes_migration_generator.rb +7 -0
  10. data/generators/dynamic_attributes_migration/templates/migration.rb +15 -0
  11. data/generators/local_migration/local_migration_generator.rb +7 -0
  12. data/generators/local_migration/templates/migration.rb +16 -0
  13. data/lib/acts_as_solr.rb +65 -0
  14. data/lib/acts_as_solr/acts_methods.rb +363 -0
  15. data/lib/acts_as_solr/class_methods.rb +240 -0
  16. data/lib/acts_as_solr/common_methods.rb +89 -0
  17. data/lib/acts_as_solr/deprecation.rb +61 -0
  18. data/lib/acts_as_solr/dynamic_attribute.rb +3 -0
  19. data/lib/acts_as_solr/instance_methods.rb +194 -0
  20. data/lib/acts_as_solr/lazy_document.rb +18 -0
  21. data/lib/acts_as_solr/local.rb +4 -0
  22. data/lib/acts_as_solr/parser_methods.rb +248 -0
  23. data/lib/acts_as_solr/search_results.rb +74 -0
  24. data/lib/acts_as_solr/solr_fixtures.rb +13 -0
  25. data/lib/acts_as_solr/tasks.rb +10 -0
  26. data/lib/acts_as_solr/tasks/database.rake +16 -0
  27. data/lib/acts_as_solr/tasks/solr.rake +142 -0
  28. data/lib/acts_as_solr/tasks/test.rake +5 -0
  29. data/lib/solr.rb +26 -0
  30. data/lib/solr/connection.rb +177 -0
  31. data/lib/solr/document.rb +75 -0
  32. data/lib/solr/exception.rb +13 -0
  33. data/lib/solr/field.rb +36 -0
  34. data/lib/solr/importer.rb +19 -0
  35. data/lib/solr/importer/array_mapper.rb +26 -0
  36. data/lib/solr/importer/delimited_file_source.rb +38 -0
  37. data/lib/solr/importer/hpricot_mapper.rb +27 -0
  38. data/lib/solr/importer/mapper.rb +51 -0
  39. data/lib/solr/importer/solr_source.rb +41 -0
  40. data/lib/solr/importer/xpath_mapper.rb +35 -0
  41. data/lib/solr/indexer.rb +52 -0
  42. data/lib/solr/request.rb +26 -0
  43. data/lib/solr/request/add_document.rb +58 -0
  44. data/lib/solr/request/base.rb +36 -0
  45. data/lib/solr/request/commit.rb +29 -0
  46. data/lib/solr/request/delete.rb +48 -0
  47. data/lib/solr/request/dismax.rb +46 -0
  48. data/lib/solr/request/index_info.rb +22 -0
  49. data/lib/solr/request/modify_document.rb +46 -0
  50. data/lib/solr/request/optimize.rb +19 -0
  51. data/lib/solr/request/ping.rb +36 -0
  52. data/lib/solr/request/select.rb +54 -0
  53. data/lib/solr/request/spellcheck.rb +30 -0
  54. data/lib/solr/request/standard.rb +406 -0
  55. data/lib/solr/request/update.rb +23 -0
  56. data/lib/solr/response.rb +27 -0
  57. data/lib/solr/response/add_document.rb +17 -0
  58. data/lib/solr/response/base.rb +42 -0
  59. data/lib/solr/response/commit.rb +15 -0
  60. data/lib/solr/response/delete.rb +13 -0
  61. data/lib/solr/response/dismax.rb +8 -0
  62. data/lib/solr/response/index_info.rb +26 -0
  63. data/lib/solr/response/modify_document.rb +17 -0
  64. data/lib/solr/response/optimize.rb +14 -0
  65. data/lib/solr/response/ping.rb +26 -0
  66. data/lib/solr/response/ruby.rb +42 -0
  67. data/lib/solr/response/select.rb +17 -0
  68. data/lib/solr/response/spellcheck.rb +20 -0
  69. data/lib/solr/response/standard.rb +65 -0
  70. data/lib/solr/response/xml.rb +39 -0
  71. data/lib/solr/solrtasks.rb +27 -0
  72. data/lib/solr/util.rb +32 -0
  73. data/lib/solr/xml.rb +44 -0
  74. data/solr/README.txt +36 -0
  75. data/solr/etc/jetty.xml +212 -0
  76. data/solr/etc/webdefault.xml +379 -0
  77. data/solr/exampledocs/books.csv +11 -0
  78. data/solr/exampledocs/hd.xml +46 -0
  79. data/solr/exampledocs/ipod_other.xml +50 -0
  80. data/solr/exampledocs/ipod_video.xml +35 -0
  81. data/solr/exampledocs/locales.xml +16 -0
  82. data/solr/exampledocs/mem.xml +58 -0
  83. data/solr/exampledocs/monitor.xml +31 -0
  84. data/solr/exampledocs/monitor2.xml +30 -0
  85. data/solr/exampledocs/mp500.xml +39 -0
  86. data/solr/exampledocs/post.jar +0 -0
  87. data/solr/exampledocs/post.sh +28 -0
  88. data/solr/exampledocs/sd500.xml +33 -0
  89. data/solr/exampledocs/solr.xml +38 -0
  90. data/solr/exampledocs/spellchecker.xml +58 -0
  91. data/solr/exampledocs/test_utf8.sh +83 -0
  92. data/solr/exampledocs/utf8-example.xml +42 -0
  93. data/solr/exampledocs/vidcard.xml +52 -0
  94. data/solr/lib/jetty-6.1.3.jar +0 -0
  95. data/solr/lib/jetty-util-6.1.3.jar +0 -0
  96. data/solr/lib/jsp-2.1/ant-1.6.5.jar +0 -0
  97. data/solr/lib/jsp-2.1/core-3.1.1.jar +0 -0
  98. data/solr/lib/jsp-2.1/jsp-2.1.jar +0 -0
  99. data/solr/lib/jsp-2.1/jsp-api-2.1.jar +0 -0
  100. data/solr/lib/servlet-api-2.5-6.1.3.jar +0 -0
  101. data/solr/multicore/README.txt +3 -0
  102. data/solr/multicore/core0/conf/schema.xml +41 -0
  103. data/solr/multicore/core0/conf/solrconfig.xml +40 -0
  104. data/solr/multicore/core1/conf/schema.xml +41 -0
  105. data/solr/multicore/core1/conf/solrconfig.xml +40 -0
  106. data/solr/multicore/exampledocs/ipod_other.xml +34 -0
  107. data/solr/multicore/exampledocs/ipod_video.xml +22 -0
  108. data/solr/multicore/solr.xml +35 -0
  109. data/solr/solr/README.txt +52 -0
  110. data/solr/solr/bin/abc +190 -0
  111. data/solr/solr/bin/abo +190 -0
  112. data/solr/solr/bin/backup +117 -0
  113. data/solr/solr/bin/backupcleaner +142 -0
  114. data/solr/solr/bin/commit +133 -0
  115. data/solr/solr/bin/optimize +134 -0
  116. data/solr/solr/bin/readercycle +129 -0
  117. data/solr/solr/bin/rsyncd-disable +77 -0
  118. data/solr/solr/bin/rsyncd-enable +76 -0
  119. data/solr/solr/bin/rsyncd-start +145 -0
  120. data/solr/solr/bin/rsyncd-stop +105 -0
  121. data/solr/solr/bin/scripts-util +99 -0
  122. data/solr/solr/bin/snapcleaner +154 -0
  123. data/solr/solr/bin/snapinstaller +198 -0
  124. data/solr/solr/bin/snappuller +269 -0
  125. data/solr/solr/bin/snappuller-disable +77 -0
  126. data/solr/solr/bin/snappuller-enable +77 -0
  127. data/solr/solr/bin/snapshooter +136 -0
  128. data/solr/solr/conf/admin-extra.html +31 -0
  129. data/solr/solr/conf/elevate.xml +36 -0
  130. data/solr/solr/conf/mapping-ISOLatin1Accent.txt +246 -0
  131. data/solr/solr/conf/protwords.txt +21 -0
  132. data/solr/solr/conf/schema.xml +132 -0
  133. data/solr/solr/conf/scripts.conf +24 -0
  134. data/solr/solr/conf/solrconfig.xml +906 -0
  135. data/solr/solr/conf/spellings.txt +2 -0
  136. data/solr/solr/conf/stopwords.txt +58 -0
  137. data/solr/solr/conf/synonyms.txt +31 -0
  138. data/solr/solr/conf/xslt/example.xsl +132 -0
  139. data/solr/solr/conf/xslt/example_atom.xsl +67 -0
  140. data/solr/solr/conf/xslt/example_rss.xsl +66 -0
  141. data/solr/solr/conf/xslt/luke.xsl +337 -0
  142. data/solr/solr/lib/localsolr.jar +0 -0
  143. data/solr/solr/lib/lucene-spatial-2.9-dev.jar +0 -0
  144. data/solr/start.jar +0 -0
  145. data/solr/webapps/solr.war +0 -0
  146. data/test/config/solr.yml +2 -0
  147. data/test/db/connections/mysql/connection.rb +11 -0
  148. data/test/db/connections/sqlite/connection.rb +8 -0
  149. data/test/db/migrate/001_create_books.rb +15 -0
  150. data/test/db/migrate/002_create_movies.rb +12 -0
  151. data/test/db/migrate/003_create_categories.rb +11 -0
  152. data/test/db/migrate/004_create_electronics.rb +16 -0
  153. data/test/db/migrate/005_create_authors.rb +12 -0
  154. data/test/db/migrate/006_create_postings.rb +9 -0
  155. data/test/db/migrate/007_create_posts.rb +13 -0
  156. data/test/db/migrate/008_create_gadgets.rb +11 -0
  157. data/test/db/migrate/009_create_dynamic_attributes.rb +15 -0
  158. data/test/db/migrate/010_create_advertises.rb +13 -0
  159. data/test/db/migrate/011_create_locals.rb +15 -0
  160. data/test/db/test.db +0 -0
  161. data/test/fixtures/advertises.yml +12 -0
  162. data/test/fixtures/authors.yml +9 -0
  163. data/test/fixtures/books.yml +13 -0
  164. data/test/fixtures/categories.yml +7 -0
  165. data/test/fixtures/db_definitions/mysql.sql +41 -0
  166. data/test/fixtures/dynamic_attributes.yml +11 -0
  167. data/test/fixtures/electronics.yml +49 -0
  168. data/test/fixtures/locals.yml +9 -0
  169. data/test/fixtures/movies.yml +9 -0
  170. data/test/fixtures/postings.yml +10 -0
  171. data/test/functional/acts_as_solr_test.rb +463 -0
  172. data/test/functional/association_indexing_test.rb +37 -0
  173. data/test/functional/faceted_search_test.rb +163 -0
  174. data/test/functional/multi_solr_search_test.rb +57 -0
  175. data/test/models/advertise.rb +6 -0
  176. data/test/models/author.rb +10 -0
  177. data/test/models/book.rb +10 -0
  178. data/test/models/category.rb +8 -0
  179. data/test/models/dynamic_attribute.rb +7 -0
  180. data/test/models/electronic.rb +25 -0
  181. data/test/models/gadget.rb +9 -0
  182. data/test/models/local.rb +7 -0
  183. data/test/models/movie.rb +17 -0
  184. data/test/models/novel.rb +2 -0
  185. data/test/models/post.rb +3 -0
  186. data/test/models/posting.rb +11 -0
  187. data/test/test_helper.rb +56 -0
  188. data/test/unit/acts_methods_shoulda.rb +95 -0
  189. data/test/unit/class_methods_shoulda.rb +85 -0
  190. data/test/unit/common_methods_shoulda.rb +111 -0
  191. data/test/unit/instance_methods_shoulda.rb +372 -0
  192. data/test/unit/lazy_document_shoulda.rb +34 -0
  193. data/test/unit/parser_instance.rb +19 -0
  194. data/test/unit/parser_methods_shoulda.rb +338 -0
  195. data/test/unit/solr_instance.rb +74 -0
  196. data/test/unit/test_helper.rb +24 -0
  197. metadata +290 -0
@@ -0,0 +1,74 @@
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
+ # Returns the highlighted fields which one has asked for..
62
+ def highlights
63
+ @solr_data[:highlights]
64
+ end
65
+
66
+ alias docs results
67
+ alias records results
68
+ alias num_found total
69
+ alias total_hits total
70
+ alias highest_score max_score
71
+ end
72
+
73
+ end
74
+
@@ -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,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,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,142 @@
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 => :environment do
5
+ require File.expand_path("#{File.dirname(__FILE__)}/../../../config/solr_environment")
6
+ FileUtils.mkdir_p(SOLR_LOGS_PATH)
7
+ FileUtils.mkdir_p(SOLR_DATA_PATH)
8
+ FileUtils.mkdir_p(SOLR_PIDS_PATH)
9
+ begin
10
+ n = Net::HTTP.new('127.0.0.1', SOLR_PORT)
11
+ n.request_head('/').value
12
+
13
+ rescue Net::HTTPServerException #responding
14
+ puts "Port #{SOLR_PORT} in use" and return
15
+
16
+ rescue Errno::ECONNREFUSED, Errno::EBADF #not responding
17
+ Dir.chdir(SOLR_PATH) do
18
+ cmd = "java #{SOLR_JVM_OPTIONS} -Djetty.logs=\"#{SOLR_LOGS_PATH}\" -Dsolr.solr.home=\"#{SOLR_CONFIG_PATH}\" -Dsolr.data.dir=\"#{SOLR_DATA_PATH}\" -Djetty.port=#{SOLR_PORT} -jar start.jar"
19
+ puts "Executing: " + cmd
20
+ windows = RUBY_PLATFORM =~ /(win|w)32$/
21
+ if windows
22
+ exec cmd
23
+ else
24
+ pid = fork do
25
+ #STDERR.close
26
+ exec cmd
27
+ end
28
+ end
29
+ sleep(5)
30
+ File.open("#{SOLR_PIDS_PATH}/#{ENV['RAILS_ENV']}_pid", "w"){ |f| f << pid} unless windows
31
+ puts "#{ENV['RAILS_ENV']} Solr started successfully on #{SOLR_PORT}, pid: #{pid}."
32
+ end
33
+ end
34
+ end
35
+
36
+ desc 'Stops Solr. Specify the environment by using: RAILS_ENV=your_env. Defaults to development if none.'
37
+ task :stop=> :environment do
38
+ require File.expand_path("#{File.dirname(__FILE__)}/../../../config/solr_environment")
39
+ fork do
40
+ file_path = "#{SOLR_PIDS_PATH}/#{ENV['RAILS_ENV']}_pid"
41
+ if File.exists?(file_path)
42
+ File.open(file_path, "r") do |f|
43
+ pid = f.readline
44
+ Process.kill('TERM', pid.to_i)
45
+ end
46
+ File.unlink(file_path)
47
+ Rake::Task["solr:destroy_index"].invoke if ENV['RAILS_ENV'] == 'test'
48
+ puts "Solr shutdown successfully."
49
+ else
50
+ puts "PID file not found at #{file_path}. Either Solr is not running or no PID file was written."
51
+ end
52
+ end
53
+ end
54
+
55
+ desc 'Remove Solr index'
56
+ task :destroy_index => :environment do
57
+ require File.expand_path("#{File.dirname(__FILE__)}/../../../config/solr_environment")
58
+ raise "In production mode. I'm not going to delete the index, sorry." if ENV['RAILS_ENV'] == "production"
59
+ if File.exists?("#{SOLR_DATA_PATH}")
60
+ Dir["#{SOLR_DATA_PATH}/index/*"].each{|f| File.unlink(f) if File.exists?(f)}
61
+ Dir.rmdir("#{SOLR_DATA_PATH}/index")
62
+ puts "Index files removed under " + ENV['RAILS_ENV'] + " environment"
63
+ end
64
+ end
65
+
66
+ # this task is by Henrik Nyh
67
+ # http://henrik.nyh.se/2007/06/rake-task-to-reindex-models-for-acts_as_solr
68
+ 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.}
69
+ task :reindex => :environment do
70
+ require File.expand_path("#{File.dirname(__FILE__)}/../../../config/solr_environment")
71
+
72
+ includes = env_array_to_constants('ONLY')
73
+ if includes.empty?
74
+ includes = Dir.glob("#{RAILS_ROOT}/app/models/*.rb").map { |path| File.basename(path, ".rb").camelize.constantize }
75
+ end
76
+ excludes = env_array_to_constants('EXCEPT')
77
+ includes -= excludes
78
+
79
+ optimize = env_to_bool('OPTIMIZE', true)
80
+ start_server = env_to_bool('START_SERVER', false)
81
+ clear_first = env_to_bool('CLEAR', true)
82
+ batch_size = ENV['BATCH'].to_i.nonzero? || 300
83
+ debug_output = env_to_bool("DEBUG", false)
84
+
85
+ RAILS_DEFAULT_LOGGER.level = ActiveSupport::BufferedLogger::INFO unless debug_output
86
+
87
+ if start_server
88
+ puts "Starting Solr server..."
89
+ Rake::Task["solr:start"].invoke
90
+ end
91
+
92
+ # Disable solr_optimize
93
+ module ActsAsSolr::CommonMethods
94
+ def blank() end
95
+ alias_method :deferred_solr_optimize, :solr_optimize
96
+ alias_method :solr_optimize, :blank
97
+ end
98
+
99
+ models = includes.select { |m| m.respond_to?(:rebuild_solr_index) }
100
+ models.each do |model|
101
+
102
+ if clear_first
103
+ puts "Clearing index for #{model}..."
104
+ ActsAsSolr::Post.execute(Solr::Request::Delete.new(:query => "#{model.solr_configuration[:type_field]}:#{model}"))
105
+ ActsAsSolr::Post.execute(Solr::Request::Commit.new)
106
+ end
107
+
108
+ puts "Rebuilding index for #{model}..."
109
+ model.rebuild_solr_index(batch_size)
110
+
111
+ end
112
+
113
+ if models.empty?
114
+ puts "There were no models to reindex."
115
+ elsif optimize
116
+ puts "Optimizing..."
117
+ models.last.deferred_solr_optimize
118
+ end
119
+
120
+ if start_server
121
+ puts "Shutting down Solr server..."
122
+ Rake::Task["solr:stop"].invoke
123
+ end
124
+
125
+ end
126
+
127
+ def env_array_to_constants(env)
128
+ env = ENV[env] || ''
129
+ env.split(/\s*,\s*/).map { |m| m.singularize.camelize.constantize }.uniq
130
+ end
131
+
132
+ def env_to_bool(env, default)
133
+ env = ENV[env] || ''
134
+ case env
135
+ when /^true$/i then true
136
+ when /^false$/i then false
137
+ else default
138
+ end
139
+ end
140
+
141
+ end
142
+
@@ -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
data/lib/solr.rb ADDED
@@ -0,0 +1,26 @@
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
+ module Solr; end
14
+ require File.expand_path("#{File.dirname(__FILE__)}/solr/exception")
15
+ require File.expand_path("#{File.dirname(__FILE__)}/solr/request")
16
+ require File.expand_path("#{File.dirname(__FILE__)}/solr/connection")
17
+ require File.expand_path("#{File.dirname(__FILE__)}/solr/response")
18
+ require File.expand_path("#{File.dirname(__FILE__)}/solr/util")
19
+ require File.expand_path("#{File.dirname(__FILE__)}/solr/xml")
20
+ require File.expand_path("#{File.dirname(__FILE__)}/solr/importer")
21
+ require File.expand_path("#{File.dirname(__FILE__)}/solr/indexer")
22
+ require File.expand_path("#{File.dirname(__FILE__)}/solr/xml")
23
+ require File.expand_path("#{File.dirname(__FILE__)}/solr/field")
24
+ require File.expand_path("#{File.dirname(__FILE__)}/solr/request/base")
25
+ require File.expand_path("#{File.dirname(__FILE__)}/solr/document")
26
+ require File.expand_path("#{File.dirname(__FILE__)}/solr/request/update")
@@ -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