onemorecloud-websolr-rails 1.1.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (166) hide show
  1. data/.document +5 -0
  2. data/.gitignore +15 -0
  3. data/LICENSE +19 -0
  4. data/README.rdoc +69 -0
  5. data/Rakefile +112 -0
  6. data/TESTING_THE_PLUGIN +25 -0
  7. data/VERSION +1 -0
  8. data/bin/websolr +8 -0
  9. data/config/solr.yml +15 -0
  10. data/config/solr_environment.rb +22 -0
  11. data/generate_rdoc.sh +13 -0
  12. data/lib/acts_as_solr.rb +59 -0
  13. data/lib/acts_methods.rb +279 -0
  14. data/lib/class_methods.rb +239 -0
  15. data/lib/common_methods.rb +89 -0
  16. data/lib/deprecation.rb +61 -0
  17. data/lib/instance_methods.rb +166 -0
  18. data/lib/lazy_document.rb +18 -0
  19. data/lib/parser_methods.rb +201 -0
  20. data/lib/search_results.rb +68 -0
  21. data/lib/solr.rb +21 -0
  22. data/lib/solr/connection.rb +179 -0
  23. data/lib/solr/document.rb +78 -0
  24. data/lib/solr/exception.rb +13 -0
  25. data/lib/solr/field.rb +39 -0
  26. data/lib/solr/importer.rb +19 -0
  27. data/lib/solr/importer/array_mapper.rb +26 -0
  28. data/lib/solr/importer/delimited_file_source.rb +38 -0
  29. data/lib/solr/importer/hpricot_mapper.rb +27 -0
  30. data/lib/solr/importer/mapper.rb +51 -0
  31. data/lib/solr/importer/solr_source.rb +43 -0
  32. data/lib/solr/importer/xpath_mapper.rb +35 -0
  33. data/lib/solr/indexer.rb +52 -0
  34. data/lib/solr/request.rb +26 -0
  35. data/lib/solr/request/add_document.rb +63 -0
  36. data/lib/solr/request/base.rb +36 -0
  37. data/lib/solr/request/commit.rb +31 -0
  38. data/lib/solr/request/delete.rb +50 -0
  39. data/lib/solr/request/dismax.rb +46 -0
  40. data/lib/solr/request/index_info.rb +22 -0
  41. data/lib/solr/request/modify_document.rb +51 -0
  42. data/lib/solr/request/optimize.rb +21 -0
  43. data/lib/solr/request/ping.rb +36 -0
  44. data/lib/solr/request/select.rb +56 -0
  45. data/lib/solr/request/spellcheck.rb +30 -0
  46. data/lib/solr/request/standard.rb +402 -0
  47. data/lib/solr/request/update.rb +23 -0
  48. data/lib/solr/response.rb +27 -0
  49. data/lib/solr/response/add_document.rb +17 -0
  50. data/lib/solr/response/base.rb +42 -0
  51. data/lib/solr/response/commit.rb +17 -0
  52. data/lib/solr/response/delete.rb +13 -0
  53. data/lib/solr/response/dismax.rb +8 -0
  54. data/lib/solr/response/index_info.rb +26 -0
  55. data/lib/solr/response/modify_document.rb +17 -0
  56. data/lib/solr/response/optimize.rb +14 -0
  57. data/lib/solr/response/ping.rb +28 -0
  58. data/lib/solr/response/ruby.rb +42 -0
  59. data/lib/solr/response/select.rb +17 -0
  60. data/lib/solr/response/spellcheck.rb +20 -0
  61. data/lib/solr/response/standard.rb +60 -0
  62. data/lib/solr/response/xml.rb +42 -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_fixtures.rb +13 -0
  67. data/lib/tasks/database.rake +18 -0
  68. data/lib/tasks/solr.rake +137 -0
  69. data/lib/tasks/test.rake +7 -0
  70. data/lib/websolr-rails.rb +1 -0
  71. data/lib/websolr.rb +1 -0
  72. data/lib/websolr_controller.rb +132 -0
  73. data/lib/websolr_option_parser.rb +58 -0
  74. data/lib/websolr_rails.rb +1 -0
  75. data/lib/websolr_rails/tasks.rb +4 -0
  76. data/solr/CHANGES.txt +1207 -0
  77. data/solr/LICENSE.txt +712 -0
  78. data/solr/NOTICE.txt +90 -0
  79. data/solr/etc/jetty.xml +205 -0
  80. data/solr/etc/webdefault.xml +379 -0
  81. data/solr/lib/easymock.jar +0 -0
  82. data/solr/lib/jetty-6.1.3.jar +0 -0
  83. data/solr/lib/jetty-util-6.1.3.jar +0 -0
  84. data/solr/lib/jsp-2.1/ant-1.6.5.jar +0 -0
  85. data/solr/lib/jsp-2.1/core-3.1.1.jar +0 -0
  86. data/solr/lib/jsp-2.1/jsp-2.1.jar +0 -0
  87. data/solr/lib/jsp-2.1/jsp-api-2.1.jar +0 -0
  88. data/solr/lib/servlet-api-2.4.jar +0 -0
  89. data/solr/lib/servlet-api-2.5-6.1.3.jar +0 -0
  90. data/solr/lib/xpp3-1.1.3.4.O.jar +0 -0
  91. data/solr/logs/.empty-dir-for-git +0 -0
  92. data/solr/solr/README.txt +52 -0
  93. data/solr/solr/bin/abc +176 -0
  94. data/solr/solr/bin/abo +176 -0
  95. data/solr/solr/bin/backup +108 -0
  96. data/solr/solr/bin/backupcleaner +142 -0
  97. data/solr/solr/bin/commit +128 -0
  98. data/solr/solr/bin/optimize +129 -0
  99. data/solr/solr/bin/readercycle +129 -0
  100. data/solr/solr/bin/rsyncd-disable +77 -0
  101. data/solr/solr/bin/rsyncd-enable +76 -0
  102. data/solr/solr/bin/rsyncd-start +145 -0
  103. data/solr/solr/bin/rsyncd-stop +105 -0
  104. data/solr/solr/bin/scripts-util +83 -0
  105. data/solr/solr/bin/snapcleaner +148 -0
  106. data/solr/solr/bin/snapinstaller +168 -0
  107. data/solr/solr/bin/snappuller +248 -0
  108. data/solr/solr/bin/snappuller-disable +77 -0
  109. data/solr/solr/bin/snappuller-enable +77 -0
  110. data/solr/solr/bin/snapshooter +109 -0
  111. data/solr/solr/conf/admin-extra.html +31 -0
  112. data/solr/solr/conf/protwords.txt +21 -0
  113. data/solr/solr/conf/schema.xml +126 -0
  114. data/solr/solr/conf/scripts.conf +24 -0
  115. data/solr/solr/conf/solrconfig.xml +458 -0
  116. data/solr/solr/conf/stopwords.txt +57 -0
  117. data/solr/solr/conf/synonyms.txt +31 -0
  118. data/solr/solr/conf/xslt/example.xsl +132 -0
  119. data/solr/solr/conf/xslt/example_atom.xsl +63 -0
  120. data/solr/solr/conf/xslt/example_rss.xsl +62 -0
  121. data/solr/start.jar +0 -0
  122. data/solr/tmp/.empty-dir-for-git +0 -0
  123. data/solr/webapps/solr.war +0 -0
  124. data/test/config/solr.yml +2 -0
  125. data/test/db/connections/mysql/connection.rb +10 -0
  126. data/test/db/connections/sqlite/connection.rb +8 -0
  127. data/test/db/migrate/001_create_books.rb +15 -0
  128. data/test/db/migrate/002_create_movies.rb +12 -0
  129. data/test/db/migrate/003_create_categories.rb +11 -0
  130. data/test/db/migrate/004_create_electronics.rb +16 -0
  131. data/test/db/migrate/005_create_authors.rb +12 -0
  132. data/test/db/migrate/006_create_postings.rb +9 -0
  133. data/test/db/migrate/007_create_posts.rb +13 -0
  134. data/test/db/migrate/008_create_gadgets.rb +11 -0
  135. data/test/fixtures/authors.yml +9 -0
  136. data/test/fixtures/books.yml +13 -0
  137. data/test/fixtures/categories.yml +7 -0
  138. data/test/fixtures/db_definitions/mysql.sql +41 -0
  139. data/test/fixtures/electronics.yml +49 -0
  140. data/test/fixtures/movies.yml +9 -0
  141. data/test/fixtures/postings.yml +10 -0
  142. data/test/functional/acts_as_solr_test.rb +413 -0
  143. data/test/functional/association_indexing_test.rb +37 -0
  144. data/test/functional/faceted_search_test.rb +163 -0
  145. data/test/functional/multi_solr_search_test.rb +51 -0
  146. data/test/models/author.rb +10 -0
  147. data/test/models/book.rb +10 -0
  148. data/test/models/category.rb +8 -0
  149. data/test/models/electronic.rb +21 -0
  150. data/test/models/gadget.rb +9 -0
  151. data/test/models/movie.rb +17 -0
  152. data/test/models/novel.rb +2 -0
  153. data/test/models/post.rb +3 -0
  154. data/test/models/posting.rb +11 -0
  155. data/test/test_helper.rb +51 -0
  156. data/test/unit/acts_methods_shoulda.rb +70 -0
  157. data/test/unit/class_methods_shoulda.rb +88 -0
  158. data/test/unit/common_methods_shoulda.rb +112 -0
  159. data/test/unit/instance_methods_shoulda.rb +326 -0
  160. data/test/unit/lazy_document_shoulda.rb +35 -0
  161. data/test/unit/parser_instance.rb +19 -0
  162. data/test/unit/parser_methods_shoulda.rb +278 -0
  163. data/test/unit/solr_instance.rb +46 -0
  164. data/test/unit/test_helper.rb +14 -0
  165. data/websolr-rails.gemspec +241 -0
  166. metadata +263 -0
@@ -0,0 +1,18 @@
1
+ module ActsAsSolr
2
+ class LazyDocument
3
+ attr_reader :id, :clazz
4
+
5
+ def initialize(id, clazz)
6
+ @id = id
7
+ @clazz = clazz
8
+ end
9
+
10
+ def method_missing(name, *args)
11
+ unless @__instance
12
+ @__instance = @clazz.find(@id)
13
+ end
14
+
15
+ @__instance.send(name, *args)
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,201 @@
1
+ module ActsAsSolr #:nodoc:
2
+ module ParserMethods
3
+ protected
4
+
5
+ # Method used by mostly all the ClassMethods when doing a search
6
+ def parse_query(query=nil, options={}, models=nil)
7
+ valid_options = [:offset, :limit, :facets, :models, :results_format, :order, :scores, :operator, :include, :lazy]
8
+ query_options = {}
9
+
10
+ return nil if (query.nil? || query.strip == '')
11
+
12
+ raise "Invalid parameters: #{(options.keys - valid_options).join(',')}" unless (options.keys - valid_options).empty?
13
+ begin
14
+ Deprecation.validate_query(options)
15
+ query_options[:start] = options[:offset]
16
+ query_options[:rows] = options[:limit]
17
+ query_options[:operator] = options[:operator]
18
+
19
+ # first steps on the facet parameter processing
20
+ if options[:facets]
21
+ query_options[:facets] = {}
22
+ query_options[:facets][:limit] = -1 # TODO: make this configurable
23
+ query_options[:facets][:sort] = :count if options[:facets][:sort]
24
+ query_options[:facets][:mincount] = 0
25
+ query_options[:facets][:mincount] = 1 if options[:facets][:zeros] == false
26
+ # override the :zeros (it's deprecated anyway) if :mincount exists
27
+ query_options[:facets][:mincount] = options[:facets][:mincount] if options[:facets][:mincount]
28
+ query_options[:facets][:fields] = options[:facets][:fields].collect{|k| "#{k}_facet"} if options[:facets][:fields]
29
+ query_options[:filter_queries] = replace_types([*options[:facets][:browse]].collect{|k| "#{k.sub!(/ *: */,"_facet:")}"}) if options[:facets][:browse]
30
+ query_options[:facets][:queries] = replace_types(options[:facets][:query].collect{|k| "#{k.sub!(/ *: */,"_t:")}"}) if options[:facets][:query]
31
+
32
+
33
+ if options[:facets][:dates]
34
+ query_options[:date_facets] = {}
35
+ # if options[:facets][:dates][:fields] exists then :start, :end, and :gap must be there
36
+ if options[:facets][:dates][:fields]
37
+ [:start, :end, :gap].each { |k| raise "#{k} must be present in faceted date query" unless options[:facets][:dates].include?(k) }
38
+ query_options[:date_facets][:fields] = []
39
+ options[:facets][:dates][:fields].each { |f|
40
+ if f.kind_of? Hash
41
+ key = f.keys[0]
42
+ query_options[:date_facets][:fields] << {"#{key}_d" => f[key]}
43
+ validate_date_facet_other_options(f[key][:other]) if f[key][:other]
44
+ else
45
+ query_options[:date_facets][:fields] << "#{f}_d"
46
+ end
47
+ }
48
+ end
49
+
50
+ query_options[:date_facets][:start] = options[:facets][:dates][:start] if options[:facets][:dates][:start]
51
+ query_options[:date_facets][:end] = options[:facets][:dates][:end] if options[:facets][:dates][:end]
52
+ query_options[:date_facets][:gap] = options[:facets][:dates][:gap] if options[:facets][:dates][:gap]
53
+ query_options[:date_facets][:hardend] = options[:facets][:dates][:hardend] if options[:facets][:dates][:hardend]
54
+ query_options[:date_facets][:filter] = replace_types([*options[:facets][:dates][:filter]].collect{|k| "#{k.sub!(/ *:(?!\d) */,"_d:")}"}) if options[:facets][:dates][:filter]
55
+
56
+ if options[:facets][:dates][:other]
57
+ validate_date_facet_other_options(options[:facets][:dates][:other])
58
+ query_options[:date_facets][:other] = options[:facets][:dates][:other]
59
+ end
60
+
61
+ end
62
+ end
63
+
64
+ if models.nil?
65
+ # TODO: use a filter query for type, allowing Solr to cache it individually
66
+ models = "AND #{solr_type_condition}"
67
+ field_list = solr_configuration[:primary_key_field]
68
+ else
69
+ field_list = "id"
70
+ end
71
+
72
+ query_options[:field_list] = [field_list, 'score']
73
+ query = "(#{query.gsub(/ *: */,"_t:")}) #{models}"
74
+ order = options[:order].split(/\s*,\s*/).collect{|e| e.gsub(/\s+/,'_t ').gsub(/\bscore_t\b/, 'score') }.join(',') if options[:order]
75
+ query_options[:query] = replace_types([query])[0] # TODO adjust replace_types to work with String or Array
76
+
77
+ if options[:order]
78
+ # TODO: set the sort parameter instead of the old ;order. style.
79
+ query_options[:query] << ';' << replace_types([order], false)[0]
80
+ end
81
+
82
+ ActsAsSolr::Post.execute(Solr::Request::Standard.new(query_options))
83
+ rescue
84
+ raise "There was a problem executing your search: #{$!} in #{$!.backtrace.first}"
85
+ end
86
+ end
87
+
88
+ def solr_type_condition
89
+ subclasses.inject("(#{solr_configuration[:type_field]}:#{self.name}") do |condition, subclass|
90
+ condition << " OR #{solr_configuration[:type_field]}:#{subclass.name}"
91
+ end << ')'
92
+ end
93
+
94
+ # Parses the data returned from Solr
95
+ def parse_results(solr_data, options = {})
96
+ results = {
97
+ :docs => [],
98
+ :total => 0
99
+ }
100
+
101
+ configuration = {
102
+ :format => :objects
103
+ }
104
+ results.update(:facets => {'facet_fields' => []}) if options[:facets]
105
+ return SearchResults.new(results) if (solr_data.nil? || solr_data.total_hits == 0)
106
+
107
+ configuration.update(options) if options.is_a?(Hash)
108
+
109
+ ids = solr_data.hits.collect {|doc| doc["#{solr_configuration[:primary_key_field]}"]}.flatten
110
+
111
+ result = find_objects(ids, options, configuration)
112
+
113
+ add_scores(result, solr_data) if configuration[:format] == :objects && options[:scores]
114
+
115
+ results.update(:facets => solr_data.data['facet_counts']) if options[:facets]
116
+ results.update({:docs => result, :total => solr_data.total_hits, :max_score => solr_data.max_score, :query_time => solr_data.data['responseHeader']['QTime']})
117
+ SearchResults.new(results)
118
+ end
119
+
120
+
121
+ def find_objects(ids, options, configuration)
122
+ result = if configuration[:lazy] && configuration[:format] != :ids
123
+ ids.collect {|id| ActsAsSolr::LazyDocument.new(id, self)}
124
+ elsif configuration[:format] == :objects
125
+ conditions = [ "#{self.table_name}.#{primary_key} in (?)", ids ]
126
+ find_options = {:conditions => conditions}
127
+ find_options[:include] = options[:include] if options[:include]
128
+ result = reorder(self.find(:all, find_options), ids)
129
+ else
130
+ ids
131
+ end
132
+
133
+ result
134
+ end
135
+
136
+ # Reorders the instances keeping the order returned from Solr
137
+ def reorder(things, ids)
138
+ ordered_things = Array.new(things.size)
139
+ raise "Out of sync! Found #{ids.size} items in index, but only #{things.size} were found in database!" unless things.size == ids.size
140
+ things.each do |thing|
141
+ position = ids.index(thing.id)
142
+ ordered_things[position] = thing
143
+ end
144
+ ordered_things
145
+ end
146
+
147
+ # Replaces the field types based on the types (if any) specified
148
+ # on the acts_as_solr call
149
+ def replace_types(strings, include_colon=true)
150
+ suffix = include_colon ? ":" : ""
151
+ if configuration[:solr_fields]
152
+ configuration[:solr_fields].each do |name, options|
153
+ solr_name = options[:as] || name.to_s
154
+ solr_type = get_solr_field_type(options[:type])
155
+ field = "#{solr_name}_#{solr_type}#{suffix}"
156
+ strings.each_with_index {|s,i| strings[i] = s.gsub(/#{solr_name.to_s}_t#{suffix}/,field) }
157
+ end
158
+ end
159
+ if configuration[:solr_includes]
160
+ configuration[:solr_includes].each do |association, options|
161
+ solr_name = options[:as] || association.to_s.singularize
162
+ solr_type = get_solr_field_type(options[:type])
163
+ field = "#{solr_name}_#{solr_type}#{suffix}"
164
+ strings.each_with_index {|s,i| strings[i] = s.gsub(/#{solr_name.to_s}_t#{suffix}/,field) }
165
+ end
166
+ end
167
+ strings
168
+ end
169
+
170
+ # Adds the score to each one of the instances found
171
+ def add_scores(results, solr_data)
172
+ with_score = []
173
+ solr_data.hits.each do |doc|
174
+ with_score.push([doc["score"],
175
+ results.find {|record| scorable_record?(record, doc) }])
176
+ end
177
+ with_score.each do |score, object|
178
+ class << object; attr_accessor :solr_score; end
179
+ object.solr_score = score
180
+ end
181
+ end
182
+
183
+ def scorable_record?(record, doc)
184
+ doc_id = doc["#{solr_configuration[:primary_key_field]}"]
185
+ if doc_id.nil?
186
+ doc_id = doc["id"]
187
+ "#{record.class.name}:#{record_id(record)}" == doc_id.first.to_s
188
+ else
189
+ record_id(record).to_s == doc_id.to_s
190
+ end
191
+ end
192
+
193
+ def validate_date_facet_other_options(options)
194
+ valid_other_options = [:after, :all, :before, :between, :none]
195
+ options = [options] unless options.kind_of? Array
196
+ bad_options = options.map {|x| x.to_sym} - valid_other_options
197
+ raise "Invalid option#{'s' if bad_options.size > 1} for faceted date's other param: #{bad_options.join(', ')}. May only be one of :after, :all, :before, :between, :none" if bad_options.size > 0
198
+ end
199
+
200
+ end
201
+ end
@@ -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,21 @@
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 'solr/exception'
15
+ require 'solr/request'
16
+ require 'solr/connection'
17
+ require 'solr/response'
18
+ require 'solr/util'
19
+ require 'solr/xml'
20
+ require 'solr/importer'
21
+ require 'solr/indexer'
@@ -0,0 +1,179 @@
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
+ require 'net/http'
14
+
15
+ # TODO: add a convenience method to POST a Solr .xml file, like Solr's example post.sh
16
+
17
+ class Solr::Connection
18
+ attr_reader :url, :autocommit, :connection
19
+
20
+ # create a connection to a solr instance using the url for the solr
21
+ # application context:
22
+ #
23
+ # conn = Solr::Connection.new("http://example.com:8080/solr")
24
+ #
25
+ # if you would prefer to have all adds/updates autocommitted,
26
+ # use :autocommit => :on
27
+ #
28
+ # conn = Solr::Connection.new('http://example.com:8080/solr',
29
+ # :autocommit => :on)
30
+
31
+ def initialize(url="http://localhost:8983/solr", opts={})
32
+ @url = URI.parse(url)
33
+ unless @url.kind_of? URI::HTTP
34
+ raise "invalid http url: #{url}"
35
+ end
36
+
37
+ # TODO: Autocommit seems nice at one level, but it currently is confusing because
38
+ # only calls to Connection#add/#update/#delete, though a Connection#send(AddDocument.new(...))
39
+ # does not autocommit. Maybe #send should check for the request types that require a commit and
40
+ # commit in #send instead of the individual methods?
41
+ @autocommit = opts[:autocommit] == :on
42
+
43
+ # Not actually opening the connection yet, just setting up the persistent connection.
44
+ @connection = Net::HTTP.new(@url.host, @url.port)
45
+
46
+ @connection.read_timeout = opts[:timeout] if opts[:timeout]
47
+ end
48
+
49
+ # add a document to the index. you can pass in either a hash
50
+ #
51
+ # conn.add(:id => 123, :title => 'Tlon, Uqbar, Orbis Tertius')
52
+ #
53
+ # or a Solr::Document
54
+ #
55
+ # conn.add(Solr::Document.new(:id => 123, :title = 'On Writing')
56
+ #
57
+ # true/false will be returned to designate success/failure
58
+
59
+ def add(doc)
60
+ request = Solr::Request::AddDocument.new(doc)
61
+ response = send(request)
62
+ commit if @autocommit
63
+ return response.ok?
64
+ end
65
+
66
+ # update a document in the index (really just an alias to add)
67
+
68
+ def update(doc)
69
+ return add(doc)
70
+ end
71
+
72
+ # performs a standard query and returns a Solr::Response::Standard
73
+ #
74
+ # response = conn.query('borges')
75
+ #
76
+ # alternative you can pass in a block and iterate over hits
77
+ #
78
+ # conn.query('borges') do |hit|
79
+ # puts hit
80
+ # end
81
+ #
82
+ # options include:
83
+ #
84
+ # :sort, :default_field, :rows, :filter_queries, :debug_query,
85
+ # :explain_other, :facets, :highlighting, :mlt,
86
+ # :operator => :or / :and
87
+ # :start => defaults to 0
88
+ # :field_list => array, defaults to ["*", "score"]
89
+
90
+ def query(query, options={}, &action)
91
+ # TODO: Shouldn't this return an exception if the Solr status is not ok? (rather than true/false).
92
+ create_and_send_query(Solr::Request::Standard, options.update(:query => query), &action)
93
+ end
94
+
95
+ # performs a dismax search and returns a Solr::Response::Standard
96
+ #
97
+ # response = conn.search('borges')
98
+ #
99
+ # options are same as query, but also include:
100
+ #
101
+ # :tie_breaker, :query_fields, :minimum_match, :phrase_fields,
102
+ # :phrase_slop, :boost_query, :boost_functions
103
+
104
+ def search(query, options={}, &action)
105
+ create_and_send_query(Solr::Request::Dismax, options.update(:query => query), &action)
106
+ end
107
+
108
+ # sends a commit message to the server
109
+ def commit(options={})
110
+ response = send(Solr::Request::Commit.new(options))
111
+ return response.ok?
112
+ end
113
+
114
+ # sends an optimize message to the server
115
+ def optimize
116
+ response = send(Solr::Request::Optimize.new)
117
+ return response.ok?
118
+ end
119
+
120
+ # pings the connection and returns true/false if it is alive or not
121
+ def ping
122
+ begin
123
+ response = send(Solr::Request::Ping.new)
124
+ return response.ok?
125
+ rescue
126
+ return false
127
+ end
128
+ end
129
+
130
+ # delete a document from the index using the document id
131
+ def delete(document_id)
132
+ response = send(Solr::Request::Delete.new(:id => document_id))
133
+ commit if @autocommit
134
+ response.ok?
135
+ end
136
+
137
+ # delete using a query
138
+ def delete_by_query(query)
139
+ response = send(Solr::Request::Delete.new(:query => query))
140
+ commit if @autocommit
141
+ response.ok?
142
+ end
143
+
144
+ def info
145
+ send(Solr::Request::IndexInfo.new)
146
+ end
147
+
148
+ # send a given Solr::Request and return a RubyResponse or XmlResponse
149
+ # depending on the type of request
150
+ def send(request)
151
+ data = post(request)
152
+ Solr::Response::Base.make_response(request, data)
153
+ end
154
+
155
+ # send the http post request to solr; for convenience there are shortcuts
156
+ # to some requests: add(), query(), commit(), delete() or send()
157
+ def post(request)
158
+ response = @connection.post(@url.path + "/" + request.handler,
159
+ request.to_s,
160
+ { "Content-Type" => request.content_type })
161
+
162
+ case response
163
+ when Net::HTTPSuccess then response.body
164
+ else
165
+ response.error!
166
+ end
167
+
168
+ end
169
+
170
+ private
171
+
172
+ def create_and_send_query(klass, options = {}, &action)
173
+ request = klass.new(options)
174
+ response = send(request)
175
+ return response unless action
176
+ response.each {|hit| action.call(hit)}
177
+ end
178
+
179
+ end