forked from longkt90/elasticsearch-rails
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathactiverecord_mapping_completion.rb
69 lines (53 loc) · 1.59 KB
/
activerecord_mapping_completion.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
require 'ansi'
require 'active_record'
require 'elasticsearch/model'
ActiveRecord::Base.logger = ActiveSupport::Logger.new(STDOUT)
ActiveRecord::Base.establish_connection( adapter: 'sqlite3', database: ":memory:" )
ActiveRecord::Schema.define(version: 1) do
create_table :articles do |t|
t.string :title
t.date :published_at
t.timestamps
end
end
class Article < ActiveRecord::Base
include Elasticsearch::Model
include Elasticsearch::Model::Callbacks
mapping do
indexes :title
indexes :title_suggest, type: 'completion', payloads: true
end
def as_indexed_json(options={})
as_json.merge \
title_suggest: {
input: title,
output: title,
payload: { url: "/articles/#{id}" }
}
end
end
Article.__elasticsearch__.client = Elasticsearch::Client.new log: true
# Create index
Article.__elasticsearch__.create_index! force: true
# Store data
Article.delete_all
Article.create title: 'Foo'
Article.create title: 'Bar'
Article.create title: 'Foo Foo'
Article.__elasticsearch__.refresh_index!
# Search and suggest
response_1 = Article.search 'foo';
puts "Article search:".ansi(:bold),
response_1.to_a.map { |d| "Title: #{d.title}" }.inspect.ansi(:bold, :yellow)
response_2 = Article.__elasticsearch__.client.suggest \
index: Article.index_name,
body: {
articles: {
text: 'foo',
completion: { field: 'title_suggest', size: 25 }
}
};
puts "Article suggest:".ansi(:bold),
response_2['articles'].first['options'].map { |d| "#{d['text']} -> #{d['payload']['url']}" }.
inspect.ansi(:bold, :green)
require 'pry'; binding.pry;