Skip to content

Commit a01586a

Browse files
committedFeb 11, 2017
[MODEL] Added an example for source filtering to the ActiveRecord associations example
See https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-source-filtering.html Related: a086de, elastic#586
1 parent a086ded commit a01586a

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed
 

‎elasticsearch-model/examples/activerecord_associations.rb

+13-3
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333

3434
create_table :authors do |t|
3535
t.string :first_name, :last_name
36+
t.string :department
3637
t.timestamps null: false
3738
end
3839

@@ -84,7 +85,7 @@ module Indexing
8485
def as_indexed_json(options={})
8586
self.as_json(
8687
include: { categories: { only: :title},
87-
authors: { methods: [:full_name], only: [:full_name] },
88+
authors: { methods: [:full_name, :department], only: [:full_name, :department] },
8889
comments: { only: :text }
8990
})
9091
end
@@ -140,7 +141,7 @@ class Comment < ActiveRecord::Base
140141

141142
# Create author
142143
#
143-
author = Author.create first_name: 'John', last_name: 'Smith'
144+
author = Author.create first_name: 'John', last_name: 'Smith', department: 'Business'
144145

145146
# Create article
146147

@@ -192,7 +193,16 @@ class Comment < ActiveRecord::Base
192193
""
193194

194195
puts "",
195-
"The indexed document:".ansi(:bold),
196+
"The whole indexed document (according to `Article#as_indexed_json`):".ansi(:bold),
197+
JSON.pretty_generate(response.results.first._source.to_hash),
198+
""
199+
200+
# Retrieve only selected fields from Elasticsearch
201+
#
202+
response = Article.search query: { match: { title: 'first' } }, _source: ['title', 'authors.full_name']
203+
204+
puts "",
205+
"Retrieve only selected fields from Elasticsearch:".ansi(:bold),
196206
JSON.pretty_generate(response.results.first._source.to_hash),
197207
""
198208

0 commit comments

Comments
 (0)
Please sign in to comment.