ssickles-tire 0.4.2

Sign up to get free protection for your applications and to get access to all the features.
Files changed (114) hide show
  1. data/.gitignore +14 -0
  2. data/.travis.yml +13 -0
  3. data/Gemfile +4 -0
  4. data/MIT-LICENSE +20 -0
  5. data/README.markdown +760 -0
  6. data/Rakefile +78 -0
  7. data/examples/rails-application-template.rb +249 -0
  8. data/examples/tire-dsl.rb +876 -0
  9. data/lib/tire.rb +52 -0
  10. data/lib/tire/alias.rb +296 -0
  11. data/lib/tire/configuration.rb +30 -0
  12. data/lib/tire/dsl.rb +43 -0
  13. data/lib/tire/http/client.rb +62 -0
  14. data/lib/tire/http/clients/curb.rb +61 -0
  15. data/lib/tire/http/response.rb +27 -0
  16. data/lib/tire/index.rb +345 -0
  17. data/lib/tire/logger.rb +60 -0
  18. data/lib/tire/model/callbacks.rb +40 -0
  19. data/lib/tire/model/import.rb +26 -0
  20. data/lib/tire/model/indexing.rb +128 -0
  21. data/lib/tire/model/naming.rb +100 -0
  22. data/lib/tire/model/percolate.rb +99 -0
  23. data/lib/tire/model/persistence.rb +72 -0
  24. data/lib/tire/model/persistence/attributes.rb +143 -0
  25. data/lib/tire/model/persistence/finders.rb +66 -0
  26. data/lib/tire/model/persistence/storage.rb +71 -0
  27. data/lib/tire/model/search.rb +305 -0
  28. data/lib/tire/results/collection.rb +114 -0
  29. data/lib/tire/results/item.rb +83 -0
  30. data/lib/tire/results/pagination.rb +54 -0
  31. data/lib/tire/rubyext/hash.rb +8 -0
  32. data/lib/tire/rubyext/ruby_1_8.rb +54 -0
  33. data/lib/tire/rubyext/symbol.rb +11 -0
  34. data/lib/tire/search.rb +160 -0
  35. data/lib/tire/search/facet.rb +70 -0
  36. data/lib/tire/search/filter.rb +28 -0
  37. data/lib/tire/search/highlight.rb +37 -0
  38. data/lib/tire/search/query.rb +151 -0
  39. data/lib/tire/search/scan.rb +114 -0
  40. data/lib/tire/search/sort.rb +25 -0
  41. data/lib/tire/tasks.rb +135 -0
  42. data/lib/tire/utils.rb +17 -0
  43. data/lib/tire/version.rb +22 -0
  44. data/test/fixtures/articles/1.json +1 -0
  45. data/test/fixtures/articles/2.json +1 -0
  46. data/test/fixtures/articles/3.json +1 -0
  47. data/test/fixtures/articles/4.json +1 -0
  48. data/test/fixtures/articles/5.json +1 -0
  49. data/test/integration/active_model_indexing_test.rb +51 -0
  50. data/test/integration/active_model_searchable_test.rb +114 -0
  51. data/test/integration/active_record_searchable_test.rb +446 -0
  52. data/test/integration/boolean_queries_test.rb +43 -0
  53. data/test/integration/count_test.rb +34 -0
  54. data/test/integration/custom_score_queries_test.rb +88 -0
  55. data/test/integration/dsl_search_test.rb +22 -0
  56. data/test/integration/explanation_test.rb +44 -0
  57. data/test/integration/facets_test.rb +232 -0
  58. data/test/integration/filtered_queries_test.rb +66 -0
  59. data/test/integration/filters_test.rb +63 -0
  60. data/test/integration/fuzzy_queries_test.rb +20 -0
  61. data/test/integration/highlight_test.rb +64 -0
  62. data/test/integration/index_aliases_test.rb +122 -0
  63. data/test/integration/index_mapping_test.rb +43 -0
  64. data/test/integration/index_store_test.rb +96 -0
  65. data/test/integration/mongoid_searchable_test.rb +309 -0
  66. data/test/integration/percolator_test.rb +111 -0
  67. data/test/integration/persistent_model_test.rb +117 -0
  68. data/test/integration/query_return_version_test.rb +70 -0
  69. data/test/integration/query_string_test.rb +52 -0
  70. data/test/integration/range_queries_test.rb +36 -0
  71. data/test/integration/reindex_test.rb +46 -0
  72. data/test/integration/results_test.rb +39 -0
  73. data/test/integration/scan_test.rb +56 -0
  74. data/test/integration/sort_test.rb +36 -0
  75. data/test/integration/text_query_test.rb +39 -0
  76. data/test/models/active_model_article.rb +31 -0
  77. data/test/models/active_model_article_with_callbacks.rb +49 -0
  78. data/test/models/active_model_article_with_custom_document_type.rb +7 -0
  79. data/test/models/active_model_article_with_custom_index_name.rb +7 -0
  80. data/test/models/active_record_models.rb +122 -0
  81. data/test/models/article.rb +15 -0
  82. data/test/models/mongoid_models.rb +97 -0
  83. data/test/models/persistent_article.rb +11 -0
  84. data/test/models/persistent_article_in_namespace.rb +12 -0
  85. data/test/models/persistent_article_with_casting.rb +28 -0
  86. data/test/models/persistent_article_with_defaults.rb +11 -0
  87. data/test/models/persistent_articles_with_custom_index_name.rb +10 -0
  88. data/test/models/supermodel_article.rb +17 -0
  89. data/test/models/validated_model.rb +11 -0
  90. data/test/test_helper.rb +88 -0
  91. data/test/unit/active_model_lint_test.rb +17 -0
  92. data/test/unit/configuration_test.rb +74 -0
  93. data/test/unit/http_client_test.rb +76 -0
  94. data/test/unit/http_response_test.rb +49 -0
  95. data/test/unit/index_alias_test.rb +275 -0
  96. data/test/unit/index_test.rb +841 -0
  97. data/test/unit/logger_test.rb +125 -0
  98. data/test/unit/model_callbacks_test.rb +116 -0
  99. data/test/unit/model_import_test.rb +71 -0
  100. data/test/unit/model_persistence_test.rb +516 -0
  101. data/test/unit/model_search_test.rb +899 -0
  102. data/test/unit/results_collection_test.rb +281 -0
  103. data/test/unit/results_item_test.rb +155 -0
  104. data/test/unit/rubyext_test.rb +60 -0
  105. data/test/unit/search_facet_test.rb +153 -0
  106. data/test/unit/search_filter_test.rb +42 -0
  107. data/test/unit/search_highlight_test.rb +46 -0
  108. data/test/unit/search_query_test.rb +242 -0
  109. data/test/unit/search_scan_test.rb +113 -0
  110. data/test/unit/search_sort_test.rb +50 -0
  111. data/test/unit/search_test.rb +455 -0
  112. data/test/unit/tire_test.rb +126 -0
  113. data/tire.gemspec +85 -0
  114. metadata +506 -0
@@ -0,0 +1,61 @@
1
+ require 'curb'
2
+
3
+ module Tire
4
+
5
+ module HTTP
6
+
7
+ module Client
8
+
9
+ class Curb
10
+ @client = ::Curl::Easy.new
11
+ @client.resolve_mode = :ipv4
12
+
13
+ # @client.verbose = true
14
+
15
+ def self.get(url, data=nil)
16
+ @client.url = url
17
+
18
+ # FIXME: Curb cannot post bodies with GET requests?
19
+ # Roy Fielding seems to approve:
20
+ # <http://tech.groups.yahoo.com/group/rest-discuss/message/9962>
21
+ if data
22
+ @client.post_body = data
23
+ @client.http_post
24
+ else
25
+ @client.http_get
26
+ end
27
+ Response.new @client.body_str, @client.response_code
28
+ end
29
+
30
+ def self.post(url, data)
31
+ @client.url = url
32
+ @client.post_body = data
33
+ @client.http_post
34
+ Response.new @client.body_str, @client.response_code
35
+ end
36
+
37
+ def self.put(url, data)
38
+ @client.url = url
39
+ @client.http_put data
40
+ Response.new @client.body_str, @client.response_code
41
+ end
42
+
43
+ def self.delete(url)
44
+ @client.url = url
45
+ @client.http_delete
46
+ Response.new @client.body_str, @client.response_code
47
+ end
48
+
49
+ def self.head(url)
50
+ @client.url = url
51
+ @client.http_head
52
+ Response.new @client.body_str, @client.response_code
53
+ end
54
+
55
+ end
56
+
57
+ end
58
+
59
+ end
60
+
61
+ end
@@ -0,0 +1,27 @@
1
+ module Tire
2
+
3
+ module HTTP
4
+
5
+ class Response
6
+ attr_reader :body, :code, :headers
7
+
8
+ def initialize(body, code, headers={})
9
+ @body, @code, @headers = body, code.to_i, headers
10
+ end
11
+
12
+ def success?
13
+ code > 0 && code < 400
14
+ end
15
+
16
+ def failure?
17
+ ! success?
18
+ end
19
+
20
+ def to_s
21
+ [code, body].join(' : ')
22
+ end
23
+ end
24
+
25
+ end
26
+
27
+ end
data/lib/tire/index.rb ADDED
@@ -0,0 +1,345 @@
1
+ module Tire
2
+ class Index
3
+
4
+ attr_reader :name, :response
5
+
6
+ def initialize(name, &block)
7
+ @name = name
8
+ block.arity < 1 ? instance_eval(&block) : block.call(self) if block_given?
9
+ end
10
+
11
+ def url
12
+ "#{Configuration.url}/#{@name}"
13
+ end
14
+
15
+ def exists?
16
+ @response = Configuration.client.head("#{url}")
17
+ @response.success?
18
+
19
+ ensure
20
+ curl = %Q|curl -I "#{url}"|
21
+ logged('HEAD', curl)
22
+ end
23
+
24
+ def delete
25
+ @response = Configuration.client.delete url
26
+ @response.success?
27
+
28
+ ensure
29
+ curl = %Q|curl -X DELETE #{url}|
30
+ logged('DELETE', curl)
31
+ end
32
+
33
+ def create(options={})
34
+ @options = options
35
+ @response = Configuration.client.post url, MultiJson.encode(options)
36
+ @response.success? ? @response : false
37
+
38
+ ensure
39
+ curl = %Q|curl -X POST #{url} -d '#{MultiJson.encode(options)}'|
40
+ logged('CREATE', curl)
41
+ end
42
+
43
+ def add_alias(alias_name, configuration={})
44
+ Alias.create(configuration.merge( :name => alias_name, :index => @name ) )
45
+ end
46
+
47
+ def remove_alias(alias_name)
48
+ Alias.find(alias_name) { |a| a.indices.delete @name }.save
49
+ end
50
+
51
+ def aliases(alias_name=nil)
52
+ alias_name ? Alias.all(@name).select { |a| a.name == alias_name }.first : Alias.all(@name)
53
+ end
54
+
55
+ def mapping
56
+ @response = Configuration.client.get("#{url}/_mapping")
57
+ MultiJson.decode(@response.body)[@name]
58
+ end
59
+
60
+ def settings
61
+ @response = Configuration.client.get("#{url}/_settings")
62
+ MultiJson.decode(@response.body)[@name]['settings']
63
+ end
64
+
65
+ def store(*args)
66
+ document, options = args
67
+ type = get_type_from_document(document)
68
+
69
+ if options
70
+ percolate = options[:percolate]
71
+ percolate = "*" if percolate === true
72
+ end
73
+
74
+ id = get_id_from_document(document)
75
+ document = convert_document_to_json(document)
76
+
77
+ url = id ? "#{self.url}/#{type}/#{id}" : "#{self.url}/#{type}/"
78
+ url += "?percolate=#{percolate}" if percolate
79
+
80
+ @response = Configuration.client.post url, document
81
+ MultiJson.decode(@response.body)
82
+
83
+ ensure
84
+ curl = %Q|curl -X POST "#{url}" -d '#{document}'|
85
+ logged([type, id].join('/'), curl)
86
+ end
87
+
88
+ def bulk_store(documents, options={})
89
+ payload = documents.map do |document|
90
+ type = get_type_from_document(document, :escape => false) # Do not URL-escape the _type
91
+ id = get_id_from_document(document)
92
+
93
+ STDERR.puts "[ERROR] Document #{document.inspect} does not have ID" unless id
94
+
95
+ output = []
96
+ output << %Q|{"index":{"_index":"#{@name}","_type":"#{type}","_id":"#{id}"}}|
97
+ output << convert_document_to_json(document)
98
+ output.join("\n")
99
+ end
100
+ payload << ""
101
+
102
+ tries = 5
103
+ count = 0
104
+
105
+ begin
106
+ response = Configuration.client.post("#{url}/_bulk", payload.join("\n"))
107
+ raise RuntimeError, "#{response.code} > #{response.body}" if response.failure?
108
+ response
109
+ rescue StandardError => error
110
+ if count < tries
111
+ count += 1
112
+ STDERR.puts "[ERROR] #{error.message}, retrying (#{count})..."
113
+ retry
114
+ else
115
+ STDERR.puts "[ERROR] Too many exceptions occured, giving up. The HTTP response was: #{error.message}"
116
+ raise if options[:raise]
117
+ end
118
+
119
+ ensure
120
+ curl = %Q|curl -X POST "#{url}/_bulk" -d '{... data omitted ...}'|
121
+ logged('BULK', curl)
122
+ end
123
+ end
124
+
125
+ def import(klass_or_collection, options={})
126
+ case
127
+ when method = options.delete(:method)
128
+ options = {:page => 1, :per_page => 1000}.merge options
129
+ while documents = klass_or_collection.send(method.to_sym, options.merge(:page => options[:page])) \
130
+ and documents.to_a.length > 0
131
+
132
+ documents = yield documents if block_given?
133
+
134
+ bulk_store documents, options
135
+ options[:page] += 1
136
+ end
137
+
138
+ when klass_or_collection.respond_to?(:map)
139
+ documents = block_given? ? yield(klass_or_collection) : klass_or_collection
140
+ bulk_store documents, options
141
+
142
+ else
143
+ raise ArgumentError, "Please pass either an Enumerable compatible class, or a collection object" +
144
+ "with a method for fetching records in batches (such as 'paginate')"
145
+ end
146
+ end
147
+
148
+ def reindex(name, options={}, &block)
149
+ new_index = Index.new(name)
150
+ new_index.create(options) unless new_index.exists?
151
+
152
+ Search::Scan.new(self.name, &block).each do |results|
153
+ new_index.bulk_store results.map do |document|
154
+ document.to_hash.except(:type, :_index, :_explanation, :_score, :_version, :highlight, :sort)
155
+ end
156
+ end
157
+ end
158
+
159
+ def remove(*args)
160
+ if args.size > 1
161
+ type, document = args
162
+ type = Utils.escape(type)
163
+ id = get_id_from_document(document) || document
164
+ else
165
+ document = args.pop
166
+ type = get_type_from_document(document)
167
+ id = get_id_from_document(document) || document
168
+ end
169
+ raise ArgumentError, "Please pass a document ID" unless id
170
+
171
+ url = "#{self.url}/#{type}/#{id}"
172
+ result = Configuration.client.delete url
173
+ MultiJson.decode(result.body) if result.success?
174
+
175
+ ensure
176
+ curl = %Q|curl -X DELETE "#{url}"|
177
+ logged(id, curl)
178
+ end
179
+
180
+ def retrieve(type, id)
181
+ raise ArgumentError, "Please pass a document ID" unless id
182
+
183
+ type = Utils.escape(type)
184
+ url = "#{self.url}/#{type}/#{id}"
185
+ @response = Configuration.client.get url
186
+
187
+ h = MultiJson.decode(@response.body)
188
+ if Configuration.wrapper == Hash then h
189
+ else
190
+ return nil if h['exists'] == false
191
+ document = h['_source'] || h['fields'] || {}
192
+ document.update('id' => h['_id'], '_type' => h['_type'], '_index' => h['_index'], '_version' => h['_version'])
193
+ Configuration.wrapper.new(document)
194
+ end
195
+
196
+ ensure
197
+ curl = %Q|curl -X GET "#{url}"|
198
+ logged(id, curl)
199
+ end
200
+
201
+ def refresh
202
+ @response = Configuration.client.post "#{url}/_refresh", ''
203
+
204
+ ensure
205
+ curl = %Q|curl -X POST "#{url}/_refresh"|
206
+ logged('_refresh', curl)
207
+ end
208
+
209
+ def open(options={})
210
+ # TODO: Remove the duplication in the execute > rescue > ensure chain
211
+ @response = Configuration.client.post "#{url}/_open", MultiJson.encode(options)
212
+ MultiJson.decode(@response.body)['ok']
213
+
214
+ ensure
215
+ curl = %Q|curl -X POST "#{url}/_open"|
216
+ logged('_open', curl)
217
+ end
218
+
219
+ def close(options={})
220
+ @response = Configuration.client.post "#{url}/_close", MultiJson.encode(options)
221
+ MultiJson.decode(@response.body)['ok']
222
+
223
+ ensure
224
+ curl = %Q|curl -X POST "#{url}/_close"|
225
+ logged('_close', curl)
226
+ end
227
+
228
+ def analyze(text, options={})
229
+ options = {:pretty => true}.update(options)
230
+ params = options.to_param
231
+ @response = Configuration.client.get "#{url}/_analyze?#{params}", text
232
+ @response.success? ? MultiJson.decode(@response.body) : false
233
+
234
+ ensure
235
+ curl = %Q|curl -X GET "#{url}/_analyze?#{params}" -d '#{text}'|
236
+ logged('_analyze', curl)
237
+ end
238
+
239
+ def register_percolator_query(name, options={}, &block)
240
+ options[:query] = Search::Query.new(&block).to_hash if block_given?
241
+
242
+ @response = Configuration.client.put "#{Configuration.url}/_percolator/#{@name}/#{name}", MultiJson.encode(options)
243
+ MultiJson.decode(@response.body)['ok']
244
+
245
+ ensure
246
+ curl = %Q|curl -X PUT "#{Configuration.url}/_percolator/#{@name}/?pretty=1" -d '#{MultiJson.encode(options)}'|
247
+ logged('_percolator', curl)
248
+ end
249
+
250
+ def unregister_percolator_query(name)
251
+ @response = Configuration.client.delete "#{Configuration.url}/_percolator/#{@name}/#{name}"
252
+ MultiJson.decode(@response.body)['ok']
253
+
254
+ ensure
255
+ curl = %Q|curl -X DELETE "#{Configuration.url}/_percolator/#{@name}"|
256
+ logged('_percolator', curl)
257
+ end
258
+
259
+ def percolate(*args, &block)
260
+ document = args.shift
261
+ type = get_type_from_document(document)
262
+
263
+ document = MultiJson.decode convert_document_to_json(document)
264
+
265
+ query = Search::Query.new(&block).to_hash if block_given?
266
+
267
+ payload = { :doc => document }
268
+ payload.update( :query => query ) if query
269
+
270
+ @response = Configuration.client.get "#{url}/#{type}/_percolate", MultiJson.encode(payload)
271
+ MultiJson.decode(@response.body)['matches']
272
+
273
+ ensure
274
+ curl = %Q|curl -X GET "#{url}/#{type}/_percolate?pretty=1" -d '#{payload.to_json}'|
275
+ logged('_percolate', curl)
276
+ end
277
+
278
+ def logged(endpoint='/', curl='')
279
+ if Configuration.logger
280
+ error = $!
281
+
282
+ Configuration.logger.log_request endpoint, @name, curl
283
+
284
+ code = @response ? @response.code : error.class rescue 200
285
+
286
+ if Configuration.logger.level.to_s == 'debug'
287
+ body = if @response
288
+ defined?(Yajl) ? Yajl::Encoder.encode(@response.body, :pretty => true) : MultiJson.encode(@response.body)
289
+ else
290
+ error.message rescue ''
291
+ end
292
+ else
293
+ body = ''
294
+ end
295
+
296
+ Configuration.logger.log_response code, nil, body
297
+ end
298
+ end
299
+
300
+ def get_type_from_document(document, options={})
301
+ options = {:escape => true}.merge(options)
302
+
303
+ old_verbose, $VERBOSE = $VERBOSE, nil # Silence Object#type deprecation warnings
304
+ type = case
305
+ when document.respond_to?(:document_type)
306
+ document.document_type
307
+ when document.is_a?(Hash)
308
+ document[:_type] || document['_type'] || document[:type] || document['type']
309
+ when document.respond_to?(:_type)
310
+ document._type
311
+ when document.respond_to?(:type) && document.type != document.class
312
+ document.type
313
+ end
314
+ $VERBOSE = old_verbose
315
+
316
+ type ||= 'document'
317
+ options[:escape] ? Utils.escape(type) : type
318
+ end
319
+
320
+ def get_id_from_document(document)
321
+ old_verbose, $VERBOSE = $VERBOSE, nil # Silence Object#id deprecation warnings
322
+ id = case
323
+ when document.is_a?(Hash)
324
+ document[:_id] || document['_id'] || document[:id] || document['id']
325
+ when document.respond_to?(:id) && document.id != document.object_id
326
+ document.id
327
+ end
328
+ $VERBOSE = old_verbose
329
+ id
330
+ end
331
+
332
+ def convert_document_to_json(document)
333
+ document = case
334
+ when document.is_a?(String)
335
+ Tire.warn "Passing the document as JSON string in Index#store has been deprecated, " +
336
+ "please pass an object which responds to `to_indexed_json` or a plain Hash."
337
+ document
338
+ when document.respond_to?(:to_indexed_json) then document.to_indexed_json
339
+ else raise ArgumentError, "Please pass a JSON string or object with a 'to_indexed_json' method," +
340
+ "'#{document.class}' given."
341
+ end
342
+ end
343
+
344
+ end
345
+ end
@@ -0,0 +1,60 @@
1
+ module Tire
2
+ class Logger
3
+
4
+ def initialize(device, options={})
5
+ @device = if device.respond_to?(:write)
6
+ device
7
+ else
8
+ File.open(device, 'a')
9
+ end
10
+ @device.sync = true if @device.respond_to?(:sync)
11
+ @options = options
12
+ at_exit { @device.close unless @device.closed? } if @device.respond_to?(:closed?) && @device.respond_to?(:close)
13
+ end
14
+
15
+ def level
16
+ @options[:level] || 'info'
17
+ end
18
+
19
+ def write(message)
20
+ @device.write message
21
+ end
22
+
23
+ def log_request(endpoint, params=nil, curl='')
24
+ # 2001-02-12 18:20:42:32 [_search] (articles,users)
25
+ #
26
+ # curl -X POST ....
27
+ #
28
+ content = "# #{time}"
29
+ content += " [#{endpoint}]"
30
+ content += " (#{params.inspect})" if params
31
+ content += "\n#\n"
32
+ content += curl
33
+ content += "\n\n"
34
+ write content
35
+ end
36
+
37
+ def log_response(status, took=nil, json='')
38
+ # 2001-02-12 18:20:42:32 [200] (4 msec)
39
+ #
40
+ # {
41
+ # "took" : 4,
42
+ # "hits" : [...]
43
+ # ...
44
+ # }
45
+ #
46
+ content = "# #{time}"
47
+ content += " [#{status}]"
48
+ content += " (#{took} msec)" if took
49
+ content += "\n#\n" unless json.to_s !~ /\S/
50
+ json.to_s.each_line { |line| content += "# #{line}" } unless json.to_s !~ /\S/
51
+ content += "\n\n"
52
+ write content
53
+ end
54
+
55
+ def time
56
+ Time.now.strftime('%Y-%m-%d %H:%M:%S:%L')
57
+ end
58
+
59
+ end
60
+ end