-
Notifications
You must be signed in to change notification settings - Fork 1
Index
Marcos G. Zimmermann edited this page Sep 26, 2023
·
12 revisions
The Esse::Index
class an abstraction of an Elasticsearch index. It's responsible for defining the index name, the index settings, the index mappings, datasources and its documents.
Here is an minimal example of an index:
class ArticlesIndex < Esse::Index
repository :article do
collection do |**context, &block|
batch = [
{ id: 1, title: 'Article 1', body: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.' },
{ id: 2, title: 'Article 2', body: 'Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium.' },
]
batch.delete_if { |item| item[:id] != context[:id] } if context[:id] # Just to simulate a filter
block.call(batch, **context)
end
document do |item, **_context|
{
_id: item[:id], # The _id is a convention to define the document id. More on this later.
title: item[:title],
body: item[:body],
}
end
end
end
Now, let's see what's happening here:
- The
ArticlesIndex
class inherits fromEsse::Index
and defines arespository
block. - The
respository
block defines a new repo identified by:article
with acollection
and adocument
. - The
collection
block is responsible for fetching data from a datasource. It may receive acontext
that can be used to filter the data and ablock
that must be called with the fetched data - The
document
block is responsible for transforming each item of collection into a Esse::Document. Note that we are using aHash
as a document to keep things simpler, but under the hood, it will be converted to aEsse::Document
object.
> ArticlesIndex.documents
=> #<Enumerator: ...>
> ArticlesIndex.documents.to_a
=> [
#<Esse::HashDocument @object={:_id=>1, :title=>"Article 1", :body=>"Lorem ipsum dolor sit amet, consectetur adipiscing elit."}, @options={}>,
#<Esse::HashDocument @object={:_id=>2, :title=>"Article 2", :body=>"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium."}, @options={}>
]
> ArticlesIndex.documents(id: 1).to_a
=> [
#<Esse::HashDocument @object={:_id=>1, :title=>"Article 1", :body=>"Lorem ipsum dolor sit amet, consectetur adipiscing elit."}, @options={}>
]
Now let's go deeper in each part of the index definition.
TODO