Skip to content
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 from Esse::Index and defines a respository block.
  • The respository block defines a new repo identified by :article with a collection and a document.
  • The collection block is responsible for fetching data from a datasource. It may receive a context that can be used to filter the data and a block 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 a Hash as a document to keep things simpler, but under the hood, it will be converted to a Esse::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.

Repository

TODO

Clone this wiki locally