forked from elastic/elasticsearch-rails
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathactive_record.rb
77 lines (64 loc) · 2.32 KB
/
active_record.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
module Elasticsearch
module Model
module Adapter
module ActiveRecord
Adapter.register self,
lambda { |klass| defined?(::ActiveRecord::Base) && klass.ancestors.include?(::ActiveRecord::Base) }
module Records
# Return the `ActiveRecord::Relation` instance
#
def records
sql_records = klass.where(id: @ids)
# Re-order records based on the order from Elasticsearch hits
# by redefining `to_a`, unless the user has called `order()`
#
sql_records.instance_exec(response['hits']['hits']) do |hits|
define_singleton_method :to_a do
self.load
@records.sort_by { |record| hits.index { |hit| hit['_id'] == record.id.to_s } }
end
end
sql_records
end
# Prevent clash with `ActiveSupport::Dependencies::Loadable`
#
def load
records.load
end
# Intercept call to order, so we can ignore the order from Elasticsearch
#
def order(*args)
sql_records = records.__send__ :order, *args
# Redefine the `to_a` method to the original one
#
sql_records.instance_exec do
define_singleton_method(:to_a) { self.load; @records }
end
sql_records
end
end
module Callbacks
def self.included(base)
base.class_eval do
after_commit lambda { __elasticsearch__.index_document }, on: [:create]
after_commit lambda { __elasticsearch__.update_document }, on: [:update]
after_commit lambda { __elasticsearch__.delete_document }, on: [:destroy]
end
end
end
module Importing
# Fetch batches of records from the database
#
# Use the [`find_in_batches`](http://api.rubyonrails.org/classes/ActiveRecord/Batches.html) method
#
def __find_in_batches(options={}, &block)
find_in_batches(options) do |batch|
batch_for_bulk = batch.as_json.map { |a| { index: { _id: a.delete('id'), data: a } } }
yield batch_for_bulk
end
end
end
end
end
end
end