paskvilwiki

up: databases & search

Elasticsearch / OpenSearch search

last updated 2026-12

update 2026 - first written for Elasticsearch 0.20 (2013), rewritten for Elasticsearch 8/9 and OpenSearch 2/3 - all the same on both, see Elasticsearch / OpenSearch. facets became aggregations, and the old top-level filter is post_filter now

ES docs, OpenSearch docs

back to Elasticsearch / OpenSearch

search can be executed across indices, with a query string as a parameter, or using a request body

search is broadcast to all the index/indices shards; to limit the scope, you can use the routing parameter - e.g. using the user ID when searching through tweets by a given user. the routing parameter may be multivalued, CSV

see also highlighting, and other topics not covered here…

request body

the request body uses query DSL

curl -XGET 'localhost:9200/twitter/_search' -H 'Content-Type: application/json' -d '{
    "query" : {
        "term" : { "user" : "kimchy" }
    }
}'
{
    "took" : 2,
    "timed_out" : false,
    "_shards" : {
        "total" : 1,
        "successful" : 1,
        "skipped" : 0,
        "failed" : 0
    },
    "hits" : {
        "total" : { "value" : 1, "relation" : "eq" },
        "max_score" : 0.2876821,
        "hits" : [
            {
                "_index" : "twitter",
                "_id" : "1",
                "_score" : 0.2876821,
                "_source" : {
                    "user" : "kimchy",
                    "post_date" : "2009-11-15T14:12:12",
                    "message" : "trying out Elasticsearch"
                }
            }
        ]
    }
}

hits.total is exact only up to 10,000 - beyond that you get "relation" : "gte". set "track_total_hits" : true for the exact count (slower)

parameters

  • timeout - search timeout, bounding the search request to be executed within the specified time; default no timeout
  • from - the starting from index of the hits to return; default 0
  • size - the number of hits to return; default 10
  • search_type - query_then_fetch (default) or dfs_query_then_fetch, which first collects term frequencies from all shards for more accurate scoring - useful only with few documents spread over several shards

URI request

a search request can be executed purely using a URI by providing request parameters

curl -XGET 'localhost:9200/twitter/_search?q=user:kimchy'

parameters

  • q - query string (maps to the query_string query, see query string query for more details)
  • df - default field to use when no field prefix is defined
  • default_operator - default operator to be used - AND or OR, default OR
  • explain - include an explanation of how scoring of each hit was computed
  • _source - false, or CSV of fields to return from the source (wildcards ok); default the whole _source
  • stored_fields - CSV of stored fields to return
  • sort - sorting to perform - fieldName, fieldName:asc, or fieldName:desc; fieldName can either be an actual field, or _score; there can be several sort parameters (CSV, order is important)
  • track_scores - when sorting, set to true in order to return the score as part of each hit
  • timeout - search timeout, limiting the execution time; all results accumulated up to the timeout are returned; defaults to no timeout
  • from - starting from index of the hits to return; defaults to 0
  • size - number of hits to return; defaults to 10
  • analyze_wildcard - should wildcard and prefix queries be analyzed or not; default false
  • lenient - ignore format based failures (like text in a numeric field); default false

query element

see query DSL for details

{
    "query" : {
        "term" : { "user" : "kimchy" }
    }
}

post_filter, aggregations and filters

when doing things like faceted navigation, sometimes only the hits need to be filtered by the chosen facet, and all the aggregations ("facets") should continue to be calculated based on the original query. the post_filter element within the search request can be used to accomplish it

note, this is different compared to putting the filter into a bool query's filter clause, since this will cause the aggregations to only process the filtered results

in other words, using

{
    "query" : { "match" : { "message" : "something" } },
    "post_filter" : { "term" : { "tag" : "green" } },
    "aggs" : { "tags" : { "terms" : { "field" : "tag" } } }
}

the post_filter will not change the aggs (the results of aggregations will be the same as without the post_filter element), while the results set will be different

but using the bool query:

{
    "query" : {
        "bool" : {
            "must" : { "match" : { "message" : "something" } },
            "filter" : { "term" : { "tag" : "green" } }
        }
    },
    "aggs" : { "tags" : { "terms" : { "field" : "tag" } } }
}

the filter clause within the bool query will change the aggs, influencing both the results set and the aggregations

to filter a single aggregation, wrap it in a filter aggregation

from and size, pagination

{
    "from" : 0, "size" : 10,
    "query" : {
        "term" : { "user" : "kimchy" }
    }
}

from + size can't go over 10,000 (index.max_result_window) - deep paging gets slower with every page. for going through more, sort on a unique field and pass the last hit's sort values as search_after:

{
    "size" : 10,
    "query" : { "match_all" : {} },
    "sort" : [ { "post_date" : "asc" }, { "id" : "asc" } ],
    "search_after" : [ "2009-11-15T14:12:12", "1" ]
}

indices

  • specific index
curl -XGET 'localhost:9200/twitter/_search?q=user:kimchy'
  • multiple indices, or wildcards
curl -XGET 'localhost:9200/twitter,facebook/_search?q=user:kimchy'
curl -XGET 'localhost:9200/tw*/_search?q=user:kimchy'
  • all indices
curl -XGET 'localhost:9200/_search?q=user:kimchy'

a missing index in a CSV list is an error (404); add ignore_unavailable=true to skip it

sorting

the sort is defined on a per field level, with the special field name _score to sort by score:

{
    "sort" : [
        { "post_date" : {"order" : "asc"} },
        "user",
        { "name" : "desc" },
        { "age" : "desc" },
        "_score"
    ],
    "query" : {
        "term" : { "user" : "kimchy" }
    }
}

the sort values for each document returned are also returned as part of the response

missing fields

the missing value can be _last (the default), _first, or a custom value (that will be used for missing docs as the sort value). for example:

{
    "sort" : [
        { "price" : {"missing" : "_last"} }
    ],
    "query" : {
        "term" : { "user" : "kimchy" }
    }
}

missing mapping for field

by default, the search request will fail if there is no mapping associated with a field (e.g. searching several indices, and the field isn't in all of them). the unmapped_type option tells what type to assume where it's not mapped, so those documents sort as if they had no value:

{
    "sort" : [
        { "price" : {"unmapped_type" : "long"} }
    ],
    "query" : {
        "term" : { "user" : "kimchy" }
    }
}

GeoDistance

you can also sort by _geo_distance (the field has to be mapped as geo_point):

{
    "sort" : [
        {
            "_geo_distance" : {
                "pin.location" : [-70, 40],
                "order" : "asc",
                "unit" : "km"
            }
        }
    ],
    "query" : {
        "term" : { "user" : "kimchy" }
    }
}

the _geo_distance pin may be provided as:

properties:         "pin.location" : { "lat" : 40, "lon" : -70 }
string:             "pin.location" : "40,-70"
geohash:            "pin.location" : "drm3btev3e86"
array:              "pin.location" : [-70, 40]

script based sorting

{
    "query" : {
        "term" : { "user" : "kimchy" }
    },
    "sort" : {
        "_script" : {
            "type" : "number",
            "script" : {
                "source" : "doc['field_name'].value * params.factor",
                "params" : {
                    "factor" : 1.1
                }
            },
            "order" : "asc"
        }
    }
}

note: to change the score rather than the sort order, use the function_score query

scores

when sorting on a field, scores are not computed. by setting track_scores to true, scores will still be computed and tracked

{
    "track_scores": true,
    "sort" : [
        { "post_date" : {"order" : "desc"} },
        { "name" : "desc" },
        { "age" : "desc" }
    ],
    "query" : {
        "term" : { "user" : "kimchy" }
    }
}

note

sorting (and aggregations) use doc values, an on-disk column store, so it doesn't eat the heap like it used to. a text field has no doc values - sort on a keyword (sub-)field instead, e.g. title.keyword. for numeric types, it is recommended to explicitly set the type - short, integer, float, …

fields

by default, the whole _source of each hit is returned

_source can be turned off with false, or limited to some fields, with wildcards and sub-objects:

{
    "_source" : ["user", "obj1.*"],
    "query" : {
        "term" : { "user" : "kimchy" }
    }
}

"_source" : false returns only the _index, _id and _score of each hit

includes and excludes

you can also specify parts of the document to be included or excluded (each of them supports multiple patterns):

{
    "query" : {
        "match_all" : {}
    },
    "_source" : {
        "includes" : ["obj1.obj2.*", "obj1.obj4.*"],
        "excludes" : ["obj1.obj3.*"]
    }
}

there's also "fields" : ["user", "post_date"], which returns the values as the mapping sees them (e.g. dates in a set format), always as arrays - and stored_fields for fields with store set to true

script fields

values may also be computed by a script:

{
    "query" : {
        "term" : { "user" : "kimchy" }
    },
    "script_fields" : {
        "test1" : {
            "script" : "doc['my_field_name'].value * 2"
        },
        "test2" : {
            "script" : {
                "source" : "doc['my_field_name'].value * params.factor",
                "params" : {
                    "factor" : 2.0
                }
            }
        },
        "test3" : {
            "script" : "params['_source']['obj1']['obj2']"
        }
    }
}

it's important to understand the difference between doc['my_field'].value and params['_source']['my_field']. the first, using the doc keyword, reads the field's doc values, which is fast. also, the doc[...] notation only allows for simple valued fields (can't return a JSON object from it), and doesn't work on text fields. the _source on the other hand causes the source to be loaded, parsed, and then only the relevant part of the JSON is returned - much slower, but it gets you anything. a document without the field makes the script fail (a null), unless it checks first - doc['my_field'].size() == 0 or params['_source']['obj1'] == null

aggregations

aggregations replaced facets - they compute summaries over the matching documents, next to the hits. there are three kinds - bucket aggregations group documents (terms, range, date_histogram, histogram, filter), metric ones compute a value (avg, sum, min, max, stats, cardinality, percentiles), and pipeline ones work on other aggregations' output

the field used for aggregations must be one with doc values - numeric, date, keyword, … not text - see mappings

you can give each aggregation a custom name, return multiple aggregations in one request, and nest them - a metric per bucket. set size to 0 if you only want the aggregations, not the hits:

{
    "size" : 0,
    "query" : { "match" : { "message" : "something" } },
    "aggs" : {
        "per_tag" : {
            "terms" : { "field" : "tag", "size" : 20 },
            "aggs" : {
                "avg_price" : { "avg" : { "field" : "price" } }
            }
        },
        "per_month" : {
            "date_histogram" : { "field" : "post_date", "calendar_interval" : "month" }
        }
    }
}

the results come back under aggregations, keyed by your names - for terms, the buckets are sorted by doc_count, and the counts are approximate when the index has more than one shard