Skip to content

Commit ded2035

Browse files
committed
[MODEL] Added a full example with mapping for the completion suggester
Related: elastic#429
1 parent 139e242 commit ded2035

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
require 'ansi'
2+
require 'active_record'
3+
require 'elasticsearch/model'
4+
5+
ActiveRecord::Base.logger = ActiveSupport::Logger.new(STDOUT)
6+
ActiveRecord::Base.establish_connection( adapter: 'sqlite3', database: ":memory:" )
7+
8+
ActiveRecord::Schema.define(version: 1) do
9+
create_table :articles do |t|
10+
t.string :title
11+
t.date :published_at
12+
t.timestamps
13+
end
14+
end
15+
16+
class Article < ActiveRecord::Base
17+
include Elasticsearch::Model
18+
include Elasticsearch::Model::Callbacks
19+
20+
mapping do
21+
indexes :title
22+
indexes :title_suggest, type: 'completion', payloads: true
23+
end
24+
25+
def as_indexed_json(options={})
26+
as_json.merge \
27+
title_suggest: {
28+
input: title,
29+
output: title,
30+
payload: { url: "/articles/#{id}" }
31+
}
32+
end
33+
end
34+
35+
Article.__elasticsearch__.client = Elasticsearch::Client.new log: true
36+
37+
# Create index
38+
39+
Article.__elasticsearch__.create_index! force: true
40+
41+
# Store data
42+
43+
Article.delete_all
44+
Article.create title: 'Foo'
45+
Article.create title: 'Bar'
46+
Article.create title: 'Foo Foo'
47+
Article.__elasticsearch__.refresh_index!
48+
49+
# Search and suggest
50+
51+
response_1 = Article.search 'foo';
52+
53+
puts "Article search:".ansi(:bold),
54+
response_1.to_a.map { |d| "Title: #{d.title}" }.inspect.ansi(:bold, :yellow)
55+
56+
response_2 = Article.__elasticsearch__.client.suggest \
57+
index: Article.index_name,
58+
body: {
59+
articles: {
60+
text: 'foo',
61+
completion: { field: 'title_suggest', size: 25 }
62+
}
63+
};
64+
65+
puts "Article suggest:".ansi(:bold),
66+
response_2['articles'].first['options'].map { |d| "#{d['text']} -> #{d['payload']['url']}" }.
67+
inspect.ansi(:bold, :green)
68+
69+
require 'pry'; binding.pry;

0 commit comments

Comments
 (0)