具有链式 DSL 的全功能 ElasticSearch Ruby 客户端
Full-Featured Elasticsearch Ruby Client with a Chainable DSL Using SearchFlip it is dead-simple to create index classes that correspond to Elasticsearch indices and to manipulate, query and aggregate these indices using a chainable, concise, yet powerful DSL. Finally, SearchFlip supports Elasticsearch 2.x, 5.x, 6.x, 7.x and 8.x as well as Opensearch 1.x and 2.x. Check section Feature Support for version dependent features.
CommentIndex.search("hello world", default_field: "title").where(visible: true).aggregate(:user_id).sort(id: "desc")
CommentIndex.aggregate(:user_id) do |aggregation|
aggregation.aggregate(histogram: { date_histogram: { field: "created_at", interval: "month" }})
end
CommentIndex.range(:created_at, gt: Date.today - 1.week, lt: Date.today).where(state: ["approved", "pending"])Checkout UPDATING.md for detailed instructions.
There are great ruby gems to work with Elasticsearch like e.g. searchkick and elasticsearch-ruby already. However, they don't have a chainable API. Compare yourself.
# elasticsearch-ruby
Comment.search(
query: {
query_string: {
query: "hello world",
default_operator: "AND"
}
}
)
# searchkick
Comment.search("hello world", where: { available: true }, order: { id: "desc" }, aggs: [:username])
# search_flip
CommentIndex.search("hello world").where(available: true).sort(id: "desc").aggregate(:username)
Finally, SearchFlip comes with a minimal set of dependencies.
SearchFlip has a great documentation. Check youself at http://www.rubydoc.info/github/mrkamel/search_flip
Add this line to your application's Gemfile:
gem 'search_flip'and then execute
$ bundleor install it via
$ gem install search_flipYou can change global config options like:
SearchFlip::Config[:environment] = "development"
SearchFlip::Config[:base_url] = "http://127.0.0.1:9200"Available config options are:
index_prefix to have a prefix added to your index names automatically. This
can be useful to separate the indices of e.g. testing and development environments.base_url to tell SearchFlip how to connect to your clusterbulk_limit a global limit for bulk requestsbulk_max_mb a global limit for the payload of bulk requestsauto_refresh tells SearchFlip to automatically refresh an index after
import, index, delete, etc operations. This is e.g. useful for testing, etc.
Defaults to false.version allows to configure the elasticsearch version no matter which
elasticsearch version is actually in use. The version information is needed to
support version dependent features. Please note that manually configuring the
version is usually not need as the version by default is determined by sending
one request to elasticsearch.SearchFlip::Config[:version] = { number: "8.1.1" }
SearchFlip::Config[:version] = { number: "2.13", distribution: "opensearch" }First, create a separate class for your index and include SearchFlip::Index.
class CommentIndex
include SearchFlip::Index
endThen tell the Index about the index name, the corresponding model and how to serialize the model for indexing.
class CommentIndex
include SearchFlip::Index
def self.index_name
"comments"
end
def self.model
Comment
end
def self.serialize(comment)
{
id: comment.id,
username: comment.username,
title: comment.title,
message: comment.message
}
end
endOptionally, you can specify a custom type_name, but note that starting with
Elasticsearch 7, types are deprecated.
class CommentIndex
# ...
def self.type_name
"comment"
end
endYou can additionally specify an index_scope which will automatically be
applied to scopes, eg. ActiveRecord::Relation objects, passed to #import,
#index, etc. This can be used to preload associations that are used when
serializing records or to restrict the records you want to index.
class CommentIndex
# ...
def self.index_scope(scope)
scope.preload(:user)
end
end
CommentIndex.import(Comment.all) # => CommentIndex.import(Comment.all.preload(:user))To specify a custom mapping:
class CommentIndex
# ...
def self.mapping
{
properties: {
# ...
}
}
end
# ...
endPlease note that you need to specify the mapping without a type name, even for Elasticsearch versions before 7, as SearchFlip will add the type name automatically if neccessary.
To specify index settings:
def self.index_settings
{
settings: {
number_of_shards: 10,
number_of_replicas: 2
}
}
endThen you can interact with the index:
CommentIndex.create_index
CommentIndex.index_exists?
CommentIndex.delete_index
CommentIndex.update_mapping
CommentIndex.close_index
CommentIndex.open_indexIndex records (automatically uses the [Bulk API]):
CommentIndex.import(Comment.all)
CommentIndex.import(Comment.first)
CommentIndex.import([Comment.find(1), Comment.find(2)])
CommentIndex.import(Comment.where("created_at > ?", Time.now - 7.days))Query records:
CommentIndex.total_entries
# => 2838
CommentIndex.search("title:hello").records
# => [#, #, ...]
CommentIndex.where(username: "mrkamel").total_entries
# => 13
CommentIndex.aggregate(:username).aggregations(:username)
# => {1=>#, 2=>... }
...Please note that you can check the request that will be send to Elasticsearch
by calling #request on the query:
CommentIndex.search("hello world").sort(id: "desc").aggregate(:username).request
# => {:query=>{:bool=>{:must=>[{:query_string=>{:query=>"hello world", :default_operator=>:AND}}]}}, ...}Delete records:
# for Elasticsearch >= 2.x and {:bool=>{:filter=>[{:term=>{:state=>"new"}}], :must=>[{:query_string=>{:query=>"text", ...}}]}}All query/filter criteria methods (#where, #where_not, #range, etc.) are available
in post filter mode as well, ie. filters/queries applied after aggregations
are calculated. Checkout the Elasticsearch docs for further info.
query = CommentIndex.aggregate(:user_id)
query = query.post_where(reviewed: true)
query = query.post_search("username:a*")Checkout PostFilterable for a complete API reference.
SearchFlip allows to elegantly specify nested aggregations, no matter how deeply nested:
query = OrderIndex.aggregate(:username, order: { revenue: "desc" }) do |aggregation|
aggregation.aggregate(revenue: { sum: { field: "price" }})
endGenerally, aggregation results returned by Elasticsearch are returned as a
SearchFlip::Result, which basically is a Hashie::Mash, such that you can
access them via:
query.aggregations(:username)["mrkamel"].revenue.valueStill, if you want to get the raw aggregations returned by Elasticsearch,
access them without supplying any aggregation name to #aggregations:
query.aggregations # => returns the raw aggregation section
query.aggregations["username"]["buckets"].detect { |bucket| bucket["key"] == "mrkamel" }["revenue"]["value"] # => 238.50Once again, the criteria methods (#where, #range, etc.) are available in
aggregations as well:
query = OrderIndex.aggregate(average_price: {}) do |aggregation|
aggregation = aggregation.match_all
aggregation = aggregation.where(user_id: current_user.id) if current_user
aggregation.aggregate(average_price: { avg: { field: "price" }})
end
query.aggregations(:average_price).average_price.valueEven various criteria for top hits aggregations can be specified elegantly:
query = ProductIndex.aggregate(sponsored: { top_hits: {} }) do |aggregation|
aggregation.sort(:rank).highlight(:title).source([:id, :title])
endCheckout Aggregatable as well as Aggregation for a complete API reference.
query = CommentIndex.suggest(:suggestion, text: "helo", term: { field: "message" })
query.suggestions(:suggestion).first["text"] # => "hello"CommentIndex.highlight([:title, :message])
CommentIndex.highlight(:title).highlight(:description)
CommentIndex.highlight(:title, require_field_match: false)
CommentIndex.highlight(title: { type: "fvh" })query = CommentIndex.highlight(:title).search("hello")
query.results[0]._hit.highlight.title # => "hello world"There are even more chainable criteria methods to make your life easier. For a full list, checkout the reference docs.
sourceIn case you want to restrict the returned fields, simply specify
the fields via #source:
CommentIndex.source([:id, :message]).search("hello world")paginate, page, perSearchFlip supports
will_paginate and
kaminari compatible pagination. Thus,
you can either use #paginate or #page in combination with #per:
CommentIndex.paginate(page: 3, per_page: 50)
CommentIndex.page(3).per(50)profileUse #profile to enable query profiling:
query = CommentIndex.profile(true)
query.raw_response["profile"] # => { "shards" => ... }preload, eager_load and includesUses the well known methods from ActiveRecord to load associated database records when fetching the respective records themselves. Works with other ORMs as well, if supported.
Using #preload:
CommentIndex.preload(:user, :post).records
PostIndex.includes(comments: :user).recordsor #eager_load
CommentIndex.eager_load(:user, :post).records
PostIndex.eager_load(comments: :user).recordsor #includes
CommentIndex.includes(:user, :post).records
PostIndex.includes(comments: :user).recordsfind_in_batchesUsed to fetch and yield records in batches using the ElasicSearch scroll API. The batch size and scroll API timeout can be specified.
CommentIndex.search("hello world").find_in_batches(batch_size: 100) do |batch|
# ...
endfind_results_in_batchesUsed like find_in_batches, but yielding the raw results (as
SearchFlip::Result objects) instead of database records.
CommentIndex.search("hello world").find_results_in_batches(batch_size: 100) do |batch|
# ...
endfind_eachLike #find_in_batches but yielding one record at a time.
CommentIndex.search("hello world").find_each(batch_size: 100) do |record|
# ...
endfind_each_resultLike #find_results_in_batches, but yielding one record at a time.
CommentIndex.search("hello world").find_each_result(batch_size: 100) do |batch|
# ...
endscrollYou can as well use the underlying scroll API directly, ie. without using higher level scrolling:
query = CommentIndex.scroll(timeout: "5m")
until query.records.empty?
# ...
query = query.scroll(id: query.scroll_id, timeout: "5m")
endfailsafeUse #failsafe to prevent any exceptions from being raised for query string
syntax errors or Elasticsearch being unavailable, etc.
CommentIndex.search("invalid/request").execute
# raises SearchFlip::ResponseError
# ...
CommentIndex.search("invalid/request").failsafe(true).execute
# => #mergeYou can merge criterias, ie. combine the attributes (constraints, settings, etc) of two individual criter
暂无开放 Issues,或尚未同步最近议题。