Elasticquery
A module for elasticsearch-rails libraries like as user-friendly query generator.
Instalation
To install using Bundler grab the latest stable version:
gem 'elasticquery'
To manually install elasticquery
via Rubygems simply gem install:
gem install elasticquery
Getting Started
First instruction
Elasticquery was designed to be customized as you need to. Providing simple methods it allows you to build flexible queries using Elastic Query DSL
class MyQuery < Elasticquery::Base
filtered do |params|
filters do
term "user.id" => params[:user_id]
range.not :age, gte: 18
end
queries do
multi_match params[:query]
end
end
end
query = MyQuery.new query: 'i typed', user_id: 5
query.build
Article.search query.build
Currently you have
Filters
Term
term category: 'Rock'
term category: 'Soul', _cache: false
term name: " "
Terms
terms a: 1, b: 2
terms a: 1, b: ""
terms a: "", b: nil
terms a: 1, b: 2, _cache: false, execution: "or"
where a: 1, b: 2, c: 3
Range
range :age, gte: 18
range :volume, gte: 1, lte: 100
range :volume, gte: 1, lte: 100, _cache: true, execution: "fielddata"
Exists
Missing
exists "last_name"
missing "last_name"
exists ""
missing ""
with 'first_name'
without 'first_name'
Not
range.not :age, lte: ' ', gte: nil
term.not category: 'Rap'
terms.not category: 'Rap', name: "Guf"
with.not
All filters are joined by AND filter.
Queries
MultiMatch
multi_match 'developers'
multi_match 'developers', fields: "_all", operator: "and", type: "best_fields"
multi_match 'Jordan', fields: ['first_name', 'last_name'], operator: "or"
multi_match ''
search 'Hello!'
Extended instruction
There are multiple ways to organize your query, using chaining calls, or custom filters.
PeopleQuery.new.queries.multi_match('hi', operator: :or).filters.term(age: 21).build
Query.new.queries./queries-chain/.filters./filters-chain/
class PeopleQuery < Elasticquery::Base
filtered do |params|
filters do
range :age, lte: prepare_age(params[:max_age])
end
end
protected
def prepare_age(param)
param.to_i
end
end
PeopleQuery.build(max_age: '42')
class ChildQuery < Elasticquery::Base
filtered do |params|
filters do
term :'category.id' => params[:category_id]
end
end
filtered do |params|
filters do
term :'author.id' => User.find(params[:user_id]).name
end
end
end
ChildQuery.build({user_id: 1, category_id: 14}) => returns both user and category filters
class ParentQuery < Elasticquery::Base
filtered do |params|
filters do
term :'category.id' => params[:category_id]
end
end
end
class ChildQuery < ParentQuery
filtered do |params|
filters do
term :'author.id' => User.find(params[:user_id]).name
end
end
end
ChildQuery.build({user_id: 1, category_id: 14}) =>
- Elasticsearch::Model support with
es
shortcut
class Article
include Elasticsearch::Model
extend Elasticquery::Es
end
Article.es.filters.term(user_id: 12).with("published_at").queries.search("Verge").results
Article.es.filters.term(user_id: 12).with("published_at").queries.search("Verge").records