### Build Search Definition Declaratively with Elasticsearch::DSL Source: https://github.com/elastic/elasticsearch-dsl-ruby/blob/main/README.md Demonstrates how to build an Elasticsearch search definition using the declarative DSL provided by the elasticsearch-dsl gem. It requires the 'elasticsearch/dsl' library and includes an example of executing the search with an Elasticsearch client. ```ruby require 'elasticsearch/dsl' include Elasticsearch::DSL definition = search do query do match title: 'test' end end definition.to_hash # => { query: { match: { title: "test"} } } require 'elasticsearch' client = Elasticsearch::Client.new trace: true client.search body: definition # curl -X GET 'http://localhost:9200/test/_search?pretty' -d '{ # "query":{ # "match":{ # "title":"test" # } # } # }' # ... # => {"took"=>10, "hits"=> {"total"=>42, "hits"=> [...] } } ``` -------------------------------- ### Configure Search Suggestions in Ruby Source: https://context7.com/elastic/elasticsearch-dsl-ruby/llms.txt The `suggest` method configures term and phrase suggestions for search-as-you-type and "did you mean" functionality. This example sets up suggestions for misspelled terms and phrases using different fields and modes. ```ruby require 'elasticsearch/dsl' include Elasticsearch::DSL definition = search do suggest :title_suggestions, { text: 'elasticsearh', # Intentional typo term: { field: 'title', suggest_mode: 'popular', min_word_length: 3 } } suggest :phrase_suggestions, { text: 'elastc serch', phrase: { field: 'title.trigram', size: 3, gram_size: 3, direct_generator: [{ field: 'title.trigram', suggest_mode: 'always' }] } } end definition.to_hash ``` -------------------------------- ### Data Aggregations in Ruby Source: https://context7.com/elastic/elasticsearch-dsl-ruby/llms.txt Shows how to perform data aggregations in Ruby using the Elasticsearch DSL. This example includes terms, average, range, and date histogram aggregations to analyze search results. Requires 'elasticsearch/dsl'. ```ruby require 'elasticsearch/dsl' include Elasticsearch::DSL definition = search do query do match category: 'electronics' end size 0 # Only return aggregation results aggregation :brands do terms do field 'brand.keyword' size 10 order _count: 'desc' end aggregation :avg_price do avg field: 'price' end aggregation :price_ranges do range field: 'price' do ranges [ { to: 100 }, { from: 100, to: 500 }, { from: 500 } ] end end end aggregation :sales_over_time do date_histogram do field 'sold_at' calendar_interval 'month' format 'yyyy-MM' min_doc_count 0 end end end definition.to_hash ``` -------------------------------- ### Implement Pagination and Size Control in Ruby Source: https://context7.com/elastic/elasticsearch-dsl-ruby/llms.txt Control the number of results and implement pagination using `size` and `from` methods. This example demonstrates basic pagination by calculating the `from` offset based on page number and items per page, and also shows source filtering to limit returned fields. ```ruby require 'elasticsearch/dsl' include Elasticsearch::DSL # Basic pagination page = 3 per_page = 20 definition = search do query do match_all end size per_page from (page - 1) * per_page # Skip first 40 results sort do by :created_at, order: 'desc' end end definition.to_hash # Source filtering to limit returned fields definition = search do query do match title: 'elasticsearch' end size 10 source [:title, :author, :published_at] stored_fields [:title] end ``` -------------------------------- ### Accessing DSL Methods with External Data in Elasticsearch::DSL Source: https://github.com/elastic/elasticsearch-dsl-ruby/blob/main/README.md Demonstrates how to use external methods to provide data for DSL constructs within the elasticsearch-dsl gem. The example shows passing a hash from a method to a 'match' query. ```ruby def match_criteria { title: 'test' } end s = search do query do match match_criteria end end s.to_hash # => { query: { match: { title: 'test' } } } ``` -------------------------------- ### Configure Search Result Highlighting in Ruby Source: https://context7.com/elastic/elasticsearch-dsl-ruby/llms.txt The `highlight` method configures how matching terms are highlighted in search results. It supports multiple fields, custom tags, fragment sizes, and various highlighting strategies. This example demonstrates highlighting in 'title' and 'content' fields with HTML encoding. ```ruby require 'elasticsearch/dsl' include Elasticsearch::DSL definition = search do query do multi_match do query 'elasticsearch performance' fields [:title, :content] end end highlight do pre_tags '' post_tags '' fields [:title, :content] field :title, fragment_size: 0, number_of_fragments: 0 field :content, fragment_size: 150, number_of_fragments: 3 encoder 'html' end end definition.to_hash ``` -------------------------------- ### Apply Post Filters After Aggregations in Ruby Source: https://context7.com/elastic/elasticsearch-dsl-ruby/llms.txt The `post_filter` method applies filtering after aggregations are computed. This allows faceted navigation where aggregations reflect unfiltered results while search hits are filtered. This example filters for blue, medium-sized shirts while retaining aggregations for all colors and sizes. ```ruby require 'elasticsearch/dsl' include Elasticsearch::DSL definition = search do query do match title: 'shirt' end aggregation :colors do terms field: 'color.keyword' end aggregation :sizes do terms field: 'size.keyword' end # Filter results but keep aggregations on full result set post_filter do bool do must do term color: 'blue' end must do term size: 'medium' end end end end definition.to_hash ``` -------------------------------- ### Group Search Results with Field Collapsing in Ruby Source: https://context7.com/elastic/elasticsearch-dsl-ruby/llms.txt The `collapse` feature groups search results by a field value, returning only the top document per group. This example groups by the 'author' field and includes inner hits for recent posts, controlling concurrent group searches. ```ruby require 'elasticsearch/dsl' include Elasticsearch::DSL definition = search do query do match content: 'elasticsearch' end collapse :author do inner_hits 'recent_posts' do size 3 sort do by :published_at, order: 'desc' end end max_concurrent_group_searches 4 end end definition.to_hash ``` -------------------------------- ### Execute Search with Faraday Client using Elasticsearch::DSL Source: https://github.com/elastic/elasticsearch-dsl-ruby/blob/main/README.md Shows how to build an Elasticsearch search definition using the elasticsearch-dsl gem and then execute it using the Faraday HTTP client. This highlights the gem's independence from specific Elasticsearch clients. ```ruby require 'elasticsearch/dsl' include Elasticsearch::DSL definition = search { query { match title: 'test' } } require 'json' require 'faraday' client = Faraday.new(url: 'http://localhost:9200') response = JSON.parse( client.post( '/_search', JSON.dump(definition.to_hash), { 'Accept' => 'application/json', 'Content-Type' => 'application/json' } ).body ) # => {"took"=>10, "hits"=> {"total"=>42, "hits"=> [...] } } ``` -------------------------------- ### Build Search Definition Imperatively with Elasticsearch::DSL Source: https://github.com/elastic/elasticsearch-dsl-ruby/blob/main/README.md Illustrates building an Elasticsearch search definition using an imperative approach with the elasticsearch-dsl gem. This method involves instantiating search objects and assigning query components. ```ruby require 'elasticsearch/dsl' include Elasticsearch::DSL definition = Search::Search.new definition.query = Search::Queries::Match.new title: 'test' definition.to_hash # => { query: { match: { title: "test"} } } ``` -------------------------------- ### suggest - Search Suggestions Source: https://context7.com/elastic/elasticsearch-dsl-ruby/llms.txt Configures term and phrase suggestions for search-as-you-type and "did you mean" functionality. ```APIDOC ## suggest - Search Suggestions ### Description Configures term and phrase suggestions for search-as-you-type and "did you mean" functionality. ### Method `suggest` method within the `search` definition. ### Endpoint N/A (Client-side configuration) ### Parameters - **suggestion_name** (String) - Required - A unique name for this suggestion set. - **suggestion_options** (Hash) - Required - Configuration for the suggestion type. - **text** (String) - Required - The text to generate suggestions for. - **term** (Hash) - Optional - Configuration for term suggestions. - **field** (String) - Required - The field to suggest terms from. - **suggest_mode** (String) - Optional - Suggestion mode (e.g., 'popular', 'always'). - **min_word_length** (Integer) - Optional - Minimum word length. - **phrase** (Hash) - Optional - Configuration for phrase suggestions. - **field** (String) - Required - The field to suggest phrases from. - **size** (Integer) - Optional - Number of suggestions to return. - **gram_size** (Integer) - Optional - The size of the n-gram. - **direct_generator** (Array) - Optional - Direct generators for phrase suggestions. ### Request Example ```ruby definition = search do suggest :title_suggestions, { text: 'elasticsearh', # Intentional typo term: { field: 'title', suggest_mode: 'popular', min_word_length: 3 } } suggest :phrase_suggestions, { text: 'elastc serch', phrase: { field: 'title.trigram', size: 3, gram_size: 3, direct_generator: [{ field: 'title.trigram', suggest_mode: 'always' }] } } end ``` ### Response #### Success Response (200) Response will contain a `suggest` key with suggestion results. #### Response Example ```json { "suggest": { "title_suggestions": { "text": "elasticsearh", "term": { "field": "title", "suggest_mode": "popular", "min_word_length": 3 } }, "phrase_suggestions": { "text": "elastc serch", "phrase": { "field": "title.trigram", "size": 3, "gram_size": 3, "direct_generator": [...] } } } } ``` ``` -------------------------------- ### Create Elasticsearch Search Definition with Ruby DSL Source: https://context7.com/elastic/elasticsearch-dsl-ruby/llms.txt Demonstrates how to create an Elasticsearch search definition using the `search` method in the Elasticsearch DSL Ruby library. It shows both declarative (block-based) and imperative (object-oriented) approaches, and how to convert the definition to a hash for use with an Elasticsearch client. ```ruby require 'elasticsearch/dsl' include Elasticsearch::DSL # Declarative style with block definition = search do query do match title: 'elasticsearch' end end definition.to_hash # => { query: { match: { title: "elasticsearch" } } } # Use with Elasticsearch client require 'elasticsearch' client = Elasticsearch::Client.new response = client.search index: 'articles', body: definition.to_hash # => {"took"=>10, "hits"=> {"total"=>{"value"=>42}, "hits"=> [...] } } # Imperative style definition = Search::Search.new definition.query = Search::Queries::Match.new title: 'elasticsearch' definition.to_hash # => { query: { match: { title: "elasticsearch" } } } ``` -------------------------------- ### Full-Text Match Query in Ruby with Elasticsearch DSL Source: https://context7.com/elastic/elasticsearch-dsl-ruby/llms.txt Illustrates how to construct a full-text `match` query using the Elasticsearch DSL Ruby library. This query analyzes text and matches documents containing specified terms, with options for operator, fuzziness, and minimum match. ```ruby require 'elasticsearch/dsl' include Elasticsearch::DSL definition = search do query do match :content do query 'how to fix my printer' operator 'and' fuzziness 'AUTO' minimum_should_match '75%' end end end definition.to_hash # => { # query: { # match: { # content: { # query: "how to fix my printer", # operator: "and", # fuzziness: "AUTO", # minimum_should_match: "75%" # } # } # } # } ``` -------------------------------- ### Pagination and Size Control Source: https://context7.com/elastic/elasticsearch-dsl-ruby/llms.txt Control the number of results returned and implement pagination using the `size` and `from` methods, along with source filtering. ```APIDOC ## Pagination and Size Control ### Description Control the number of results returned and implement pagination using `size` and `from` methods. Also includes source filtering to limit returned fields. ### Method `size`, `from`, and `source` methods within the `search` definition. ### Endpoint N/A (Client-side configuration) ### Parameters #### Request Body (within `search` definition) - **size** (Integer) - Optional - The number of hits to return per page. Defaults to 10. - **from** (Integer) - Optional - The starting offset for pagination. Defaults to 0. - **source** (Array or Boolean) - Optional - Specifies which fields to include or exclude in the `_source` field. Can be an array of field names or `false` to disable source retrieval. - **stored_fields** (Array) - Optional - Specifies which fields to return from the `fields` parameter (deprecated in favor of `source`). ### Request Example ```ruby # Basic pagination page = 3 per_page = 20 definition = search do query do match_all end size per_page from (page - 1) * per_page # Skip first 40 results sort do by :created_at, order: 'desc' end end # Source filtering to limit returned fields definition = search do query do match title: 'elasticsearch' end size 10 source [:title, :author, :published_at] stored_fields [:title] # Deprecated end ``` ### Response #### Success Response (200) Response will contain a `hits` array with the specified number of documents, starting from the `from` offset. The `_source` field will contain only the requested fields. #### Response Example ```json { "query": { "match_all": {} }, "size": 20, "from": 40, "sort": [{ "created_at": { "order": "desc" } }] } { "query": { "match": { "title": "elasticsearch" } }, "size": 10, "_source": ["title", "author", "published_at"] } ``` ``` -------------------------------- ### Result Sorting in Ruby Source: https://context7.com/elastic/elasticsearch-dsl-ruby/llms.txt Demonstrates how to sort search results in Ruby using the Elasticsearch DSL. Includes sorting by date, score, and a field with missing value handling. Also shows geo-distance sorting. Requires 'elasticsearch/dsl'. ```ruby require 'elasticsearch/dsl' include Elasticsearch::DSL definition = search do query do match title: 'elasticsearch' end sort do by :published_at, order: 'desc' by :_score by :title, order: 'asc', missing: '_last' end end definition.to_hash # Geo-distance sorting definition = search do query do match_all end sort do by :_geo_distance, { location: { lat: 40.7128, lon: -74.0060 }, order: 'asc', unit: 'km' } end end ``` -------------------------------- ### Highlight - Search Result Highlighting Source: https://context7.com/elastic/elasticsearch-dsl-ruby/llms.txt Configure how matching terms are highlighted in search results, supporting multiple fields, custom tags, fragment sizes, and various highlighting strategies. ```APIDOC ## highlight - Search Result Highlighting ### Description Configures how matching terms are highlighted in search results. Supports multiple fields, custom tags, fragment sizes, and various highlighting strategies. ### Method `highlight` block within the `search` definition. ### Endpoint N/A (Client-side configuration) ### Parameters #### Request Body (within `highlight` block) - **pre_tags** (Array) - Optional - Tags to be prepended to highlighted terms. - **post_tags** (Array) - Optional - Tags to be appended to highlighted terms. - **fields** (Array or Hash) - Required - Fields to apply highlighting to. Can be an array of field names or a hash for field-specific configurations. - **field_name** (Hash) - Optional - Configuration for a specific field. - **fragment_size** (Integer) - Optional - Maximum size of a fragment in characters. - **number_of_fragments** (Integer) - Optional - Maximum number of fragments to return. - **encoder** (String) - Optional - The encoder to use for highlighting (e.g., 'html'). ### Request Example ```ruby definition = search do query do multi_match do query 'elasticsearch performance' fields [:title, :content] end end highlight do pre_tags '' post_tags '' fields [:title, :content] field :title, fragment_size: 0, number_of_fragments: 0 field :content, fragment_size: 150, number_of_fragments: 3 encoder 'html' end end ``` ### Response #### Success Response (200) Response will contain a `highlight` key with highlighted snippets for matching terms. #### Response Example ```json { "query": { "multi_match": { "query": "elasticsearch performance", "fields": ["title", "content"] } }, "highlight": { "pre_tags": [""], "post_tags": [""], "encoder": "html", "fields": { "title": { "fragment_size": 0, "number_of_fragments": 0 }, "content": { "fragment_size": 150, "number_of_fragments": 3 } } } } ``` ``` -------------------------------- ### Build and Execute Complex Elasticsearch Search with Ruby Client Source: https://context7.com/elastic/elasticsearch-dsl-ruby/llms.txt This Ruby code defines a class `ArticleSearch` that constructs a complex Elasticsearch query using the `elasticsearch-dsl` gem. It includes multi-match query with fuzziness, term and range filters, highlighting, aggregations, and custom sorting. The `execute` method integrates with the official `elasticsearch-ruby` client to send the query to Elasticsearch. ```ruby require 'elasticsearch/dsl' require 'elasticsearch' class ArticleSearch include Elasticsearch::DSL def initialize(params) @query = params[:q] @category = params[:category] @date_from = params[:from] @page = params[:page] || 1 @per_page = params[:per_page] || 10 end def search_definition search do query do bool do must do multi_match do query @query fields ['title^3', 'content', 'tags^2'] type 'best_fields' fuzziness 'AUTO' end end if @query.present? filter do term category: @category end if @category.present? filter do range :published_at do gte @date_from end end if @date_from.present? end end highlight do fields [:title, :content] pre_tags '' post_tags '' end aggregation :categories do terms field: 'category.keyword', size: 20 end aggregation :monthly do date_histogram do field 'published_at' calendar_interval 'month' end end sort do by :_score by :published_at, order: 'desc' end size @per_page from (@page - 1) * @per_page end end def execute client = Elasticsearch::Client.new(log: true) client.search(index: 'articles', body: search_definition.to_hash) end end # Usage search = ArticleSearch.new( q: 'elasticsearch tutorial', category: 'technology', from: '2023-01-01', page: 1, per_page: 10 ) response = search.execute ``` -------------------------------- ### Multi-Field Match Query in Ruby with Elasticsearch DSL Source: https://context7.com/elastic/elasticsearch-dsl-ruby/llms.txt Shows how to create a `multi_match` query using the Elasticsearch DSL Ruby library, which searches across multiple fields simultaneously. It supports various matching types and options like operator and tie-breaker. ```ruby require 'elasticsearch/dsl' include Elasticsearch::DSL definition = search do query do multi_match do query 'elasticsearch guide' fields [:title, :abstract, :content] type 'best_fields' operator 'and' tie_breaker 0.3 end end end definition.to_hash # => { # query: { # multi_match: { # query: "elasticsearch guide", # fields: [:title, :abstract, :content], # type: "best_fields", # operator: "and", # tie_breaker: 0.3 # } # } # } ``` -------------------------------- ### Defining Subqueries in External Methods with Elasticsearch::DSL Source: https://github.com/elastic/elasticsearch-dsl-ruby/blob/main/README.md Explains how to define subqueries within external methods when using the elasticsearch-dsl gem. It requires passing 'self' to the method and using 'instance_eval' to ensure the subquery has access to the correct scope. ```ruby def not_clause(obj) obj.instance_eval do _not do term color: 'red' end end end s = search do query do filtered do filter do not_clause(self) end end end end s.to_hash # => { query: { filtered: { filter: { not: { term: { color: 'red' } } } } } } ``` -------------------------------- ### Boolean Compound Query in Ruby with Elasticsearch DSL Source: https://context7.com/elastic/elasticsearch-dsl-ruby/llms.txt Demonstrates the construction of a `bool` query using the Elasticsearch DSL Ruby library. This query combines multiple clauses (must, should, must_not, filter) using boolean logic for precise control over document scoring and filtering. ```ruby require 'elasticsearch/dsl' include Elasticsearch::DSL definition = search do query do bool do must do term category: 'electronics' end must do range :price do gte 100 lte 500 end end should do match brand: 'premium' end must_not do term status: 'discontinued' end filter do term in_stock: true end minimum_should_match 1 boost 1.5 end end end definition.to_hash # => { # query: { # bool: { # must: [ # { term: { category: "electronics" } }, # { range: { price: { gte: 100, lte: 500 } } } # ], # should: [{ match: { brand: "premium" } }], # must_not: [{ term: { status: "discontinued" } }], # filter: [{ term: { in_stock: true } }], # minimum_should_match: 1, # boost: 1.5 # } # } # } ``` -------------------------------- ### Nested Document Query in Ruby Source: https://context7.com/elastic/elasticsearch-dsl-ruby/llms.txt Demonstrates how to perform a 'nested' query in Ruby using the Elasticsearch DSL. This query searches within nested objects and allows control over scoring with 'score_mode'. It requires the 'elasticsearch/dsl' gem. ```ruby require 'elasticsearch/dsl' include Elasticsearch::DSL definition = search do query do nested do path 'comments' score_mode 'avg' query do bool do must do match 'comments.text': 'elasticsearch' end must do range 'comments.date' do gte '2023-01-01' end end end end end end end definition.to_hash ``` -------------------------------- ### filter - Post Filter Source: https://context7.com/elastic/elasticsearch-dsl-ruby/llms.txt Applies filtering after aggregations are computed, allowing faceted navigation where aggregations reflect unfiltered results while search hits are filtered. ```APIDOC ## filter - Post Filter ### Description Applies filtering after aggregations are computed, allowing faceted navigation where aggregations reflect unfiltered results while search hits are filtered. ### Method `post_filter` block within the `search` definition. ### Endpoint N/A (Client-side configuration) ### Parameters #### Request Body (within `post_filter` block) - **Query DSL** - Required - Any valid Elasticsearch Query DSL to define the filter criteria. ### Request Example ```ruby definition = search do query do match title: 'shirt' end aggregation :colors do terms field: 'color.keyword' end aggregation :sizes do terms field: 'size.keyword' end # Filter results but keep aggregations on full result set post_filter do bool do must do term color: 'blue' end must do term size: 'medium' end end end end ``` ### Response #### Success Response (200) Response will contain filtered search hits, while aggregations are computed on the unfiltered set. #### Response Example ```json { "query": { "match": { "title": "shirt" } }, "aggregations": { "colors": { "terms": { "field": "color.keyword" } }, "sizes": { "terms": { "field": "size.keyword" } } }, "post_filter": { "bool": { "must": [ { "term": { "color": "blue" } }, { "term": { "size": "medium" } } ] } } } ``` ``` -------------------------------- ### collapse - Field Collapsing Source: https://context7.com/elastic/elasticsearch-dsl-ruby/llms.txt Groups search results by a field value, returning only the top document per group. Useful for deduplication or showing one result per category. ```APIDOC ## collapse - Field Collapsing ### Description Groups search results by a field value, returning only the top document per group. Useful for deduplication or showing one result per category. ### Method `collapse` method within the `search` definition. ### Endpoint N/A (Client-side configuration) ### Parameters #### Path Parameters - **field_name** (String) - Required - The field to group results by. #### Request Body (within `collapse` block) - **inner_hits** (Hash) - Optional - Defines nested search results for each collapsed group. - **name** (String) - Required - Name for the inner hits. - **size** (Integer) - Optional - Number of inner hits to return. - **sort** (Hash) - Optional - Sorting configuration for inner hits. - **max_concurrent_group_searches** (Integer) - Optional - Maximum number of concurrent group searches. ### Request Example ```ruby definition = search do query do match content: 'elasticsearch' end collapse :author do inner_hits 'recent_posts' do size 3 sort do by :published_at, order: 'desc' end end max_concurrent_group_searches 4 end end ``` ### Response #### Success Response (200) Response will contain a `collapse` key with grouped results and optionally `inner_hits`. #### Response Example ```json { "query": { "match": { "content": "elasticsearch" } }, "collapse": { "field": ":author", "inner_hits": { "name": "recent_posts", "size": 3, "sort": [{ "published_at": { "order": "desc" } }] }, "max_concurrent_group_searches": 4 } } ``` ``` -------------------------------- ### Custom Scoring Query (function_score) in Ruby Source: https://context7.com/elastic/elasticsearch-dsl-ruby/llms.txt Illustrates the use of the 'function_score' query in Ruby for custom scoring. It allows modifying document scores using decay functions, field values, and scripts, with options for 'score_mode' and 'boost_mode'. Requires 'elasticsearch/dsl'. ```ruby require 'elasticsearch/dsl' include Elasticsearch::DSL definition = search do query do function_score do query do match title: 'vacation rentals' end functions << { gauss: { price: { origin: 150, scale: 50 } }, weight: 2 } functions << { gauss: { location: { origin: '40.7128,-74.0060', scale: '5km' } }, weight: 3 } functions << { field_value_factor: { field: 'reviews_count', factor: 1.2, modifier: 'sqrt' } } score_mode 'sum' boost_mode 'multiply' max_boost 10 end end end definition.to_hash ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.