- Elasticsearch Guide: other versions:
- What’s new in 8.17
- Elasticsearch basics
- Quick starts
- Set up Elasticsearch
- Run Elasticsearch locally
- Installing Elasticsearch
- Configuring Elasticsearch
- Important Elasticsearch configuration
- Secure settings
- Auditing settings
- Circuit breaker settings
- Cluster-level shard allocation and routing settings
- Miscellaneous cluster settings
- Cross-cluster replication settings
- Discovery and cluster formation settings
- Data stream lifecycle settings
- Field data cache settings
- Local gateway settings
- Health Diagnostic settings
- Index lifecycle management settings
- Index management settings
- Index recovery settings
- Indexing buffer settings
- Inference settings
- License settings
- Machine learning settings
- Monitoring settings
- Node settings
- Networking
- Node query cache settings
- Path settings
- Search settings
- Security settings
- Shard request cache settings
- Snapshot and restore settings
- Transforms settings
- Thread pools
- Watcher settings
- Set JVM options
- Important system configuration
- Bootstrap Checks
- Heap size check
- File descriptor check
- Memory lock check
- Maximum number of threads check
- Max file size check
- Maximum size virtual memory check
- Maximum map count check
- Client JVM check
- Use serial collector check
- System call filter check
- OnError and OnOutOfMemoryError checks
- Early-access check
- All permission check
- Discovery configuration check
- Bootstrap Checks for X-Pack
- Starting Elasticsearch
- Stopping Elasticsearch
- Discovery and cluster formation
- Add and remove nodes in your cluster
- Full-cluster restart and rolling restart
- Remote clusters
- Plugins
- Upgrade Elasticsearch
- Index modules
- Mapping
- Dynamic mapping
- Explicit mapping
- Runtime fields
- Field data types
- Aggregate metric
- Alias
- Arrays
- Binary
- Boolean
- Completion
- Date
- Date nanoseconds
- Dense vector
- Flattened
- Geopoint
- Geoshape
- Histogram
- IP
- Join
- Keyword
- Nested
- Numeric
- Object
- Pass-through object
- Percolator
- Point
- Range
- Rank feature
- Rank features
- Search-as-you-type
- Semantic text
- Shape
- Sparse vector
- Text
- Token count
- Unsigned long
- Version
- Metadata fields
- Mapping parameters
analyzer
coerce
copy_to
doc_values
dynamic
eager_global_ordinals
enabled
format
ignore_above
index.mapping.ignore_above
ignore_malformed
index
index_options
index_phrases
index_prefixes
meta
fields
normalizer
norms
null_value
position_increment_gap
properties
search_analyzer
similarity
store
subobjects
term_vector
- Mapping limit settings
- Removal of mapping types
- Text analysis
- Overview
- Concepts
- Configure text analysis
- Built-in analyzer reference
- Tokenizer reference
- Token filter reference
- Apostrophe
- ASCII folding
- CJK bigram
- CJK width
- Classic
- Common grams
- Conditional
- Decimal digit
- Delimited payload
- Dictionary decompounder
- Edge n-gram
- Elision
- Fingerprint
- Flatten graph
- Hunspell
- Hyphenation decompounder
- Keep types
- Keep words
- Keyword marker
- Keyword repeat
- KStem
- Length
- Limit token count
- Lowercase
- MinHash
- Multiplexer
- N-gram
- Normalization
- Pattern capture
- Pattern replace
- Phonetic
- Porter stem
- Predicate script
- Remove duplicates
- Reverse
- Shingle
- Snowball
- Stemmer
- Stemmer override
- Stop
- Synonym
- Synonym graph
- Trim
- Truncate
- Unique
- Uppercase
- Word delimiter
- Word delimiter graph
- Character filters reference
- Normalizers
- Index templates
- Data streams
- Ingest pipelines
- Example: Parse logs
- Enrich your data
- Processor reference
- Append
- Attachment
- Bytes
- Circle
- Community ID
- Convert
- CSV
- Date
- Date index name
- Dissect
- Dot expander
- Drop
- Enrich
- Fail
- Fingerprint
- Foreach
- Geo-grid
- GeoIP
- Grok
- Gsub
- HTML strip
- Inference
- IP Location
- Join
- JSON
- KV
- Lowercase
- Network direction
- Pipeline
- Redact
- Registered domain
- Remove
- Rename
- Reroute
- Script
- Set
- Set security user
- Sort
- Split
- Terminate
- Trim
- Uppercase
- URL decode
- URI parts
- User agent
- Ingest pipelines in Search
- Aliases
- Search your data
- Re-ranking
- Query DSL
- Aggregations
- Bucket aggregations
- Adjacency matrix
- Auto-interval date histogram
- Categorize text
- Children
- Composite
- Date histogram
- Date range
- Diversified sampler
- Filter
- Filters
- Frequent item sets
- Geo-distance
- Geohash grid
- Geohex grid
- Geotile grid
- Global
- Histogram
- IP prefix
- IP range
- Missing
- Multi Terms
- Nested
- Parent
- Random sampler
- Range
- Rare terms
- Reverse nested
- Sampler
- Significant terms
- Significant text
- Terms
- Time series
- Variable width histogram
- Subtleties of bucketing range fields
- Metrics aggregations
- Pipeline aggregations
- Average bucket
- Bucket script
- Bucket count K-S test
- Bucket correlation
- Bucket selector
- Bucket sort
- Change point
- Cumulative cardinality
- Cumulative sum
- Derivative
- Extended stats bucket
- Inference bucket
- Max bucket
- Min bucket
- Moving function
- Moving percentiles
- Normalize
- Percentiles bucket
- Serial differencing
- Stats bucket
- Sum bucket
- Bucket aggregations
- Geospatial analysis
- Connectors
- EQL
- ES|QL
- SQL
- Overview
- Getting Started with SQL
- Conventions and Terminology
- Security
- SQL REST API
- SQL Translate API
- SQL CLI
- SQL JDBC
- SQL ODBC
- SQL Client Applications
- SQL Language
- Functions and Operators
- Comparison Operators
- Logical Operators
- Math Operators
- Cast Operators
- LIKE and RLIKE Operators
- Aggregate Functions
- Grouping Functions
- Date/Time and Interval Functions and Operators
- Full-Text Search Functions
- Mathematical Functions
- String Functions
- Type Conversion Functions
- Geo Functions
- Conditional Functions And Expressions
- System Functions
- Reserved keywords
- SQL Limitations
- Scripting
- Data management
- ILM: Manage the index lifecycle
- Tutorial: Customize built-in policies
- Tutorial: Automate rollover
- Index management in Kibana
- Overview
- Concepts
- Index lifecycle actions
- Configure a lifecycle policy
- Migrate index allocation filters to node roles
- Troubleshooting index lifecycle management errors
- Start and stop index lifecycle management
- Manage existing indices
- Skip rollover
- Restore a managed data stream or index
- Data tiers
- Autoscaling
- Monitor a cluster
- Roll up or transform your data
- Set up a cluster for high availability
- Snapshot and restore
- Secure the Elastic Stack
- Elasticsearch security principles
- Start the Elastic Stack with security enabled automatically
- Manually configure security
- Updating node security certificates
- User authentication
- Built-in users
- Service accounts
- Internal users
- Token-based authentication services
- User profiles
- Realms
- Realm chains
- Security domains
- Active Directory user authentication
- File-based user authentication
- LDAP user authentication
- Native user authentication
- OpenID Connect authentication
- PKI user authentication
- SAML authentication
- Kerberos authentication
- JWT authentication
- Integrating with other authentication systems
- Enabling anonymous access
- Looking up users without authentication
- Controlling the user cache
- Configuring SAML single-sign-on on the Elastic Stack
- Configuring single sign-on to the Elastic Stack using OpenID Connect
- User authorization
- Built-in roles
- Defining roles
- Role restriction
- Security privileges
- Document level security
- Field level security
- Granting privileges for data streams and aliases
- Mapping users and groups to roles
- Setting up field and document level security
- Submitting requests on behalf of other users
- Configuring authorization delegation
- Customizing roles and authorization
- Enable audit logging
- Restricting connections with IP filtering
- Securing clients and integrations
- Operator privileges
- Troubleshooting
- Some settings are not returned via the nodes settings API
- Authorization exceptions
- Users command fails due to extra arguments
- Users are frequently locked out of Active Directory
- Certificate verification fails for curl on Mac
- SSLHandshakeException causes connections to fail
- Common SSL/TLS exceptions
- Common Kerberos exceptions
- Common SAML issues
- Internal Server Error in Kibana
- Setup-passwords command fails due to connection failure
- Failures due to relocation of the configuration files
- Limitations
- Watcher
- Cross-cluster replication
- Data store architecture
- REST APIs
- API conventions
- Common options
- REST API compatibility
- Autoscaling APIs
- Behavioral Analytics APIs
- Compact and aligned text (CAT) APIs
- cat aliases
- cat allocation
- cat anomaly detectors
- cat component templates
- cat count
- cat data frame analytics
- cat datafeeds
- cat fielddata
- cat health
- cat indices
- cat master
- cat nodeattrs
- cat nodes
- cat pending tasks
- cat plugins
- cat recovery
- cat repositories
- cat segments
- cat shards
- cat snapshots
- cat task management
- cat templates
- cat thread pool
- cat trained model
- cat transforms
- Cluster APIs
- Cluster allocation explain
- Cluster get settings
- Cluster health
- Health
- Cluster reroute
- Cluster state
- Cluster stats
- Cluster update settings
- Nodes feature usage
- Nodes hot threads
- Nodes info
- Prevalidate node removal
- Nodes reload secure settings
- Nodes stats
- Cluster Info
- Pending cluster tasks
- Remote cluster info
- Task management
- Voting configuration exclusions
- Create or update desired nodes
- Get desired nodes
- Delete desired nodes
- Get desired balance
- Reset desired balance
- Cross-cluster replication APIs
- Connector APIs
- Create connector
- Delete connector
- Get connector
- List connectors
- Update connector API key id
- Update connector configuration
- Update connector index name
- Update connector features
- Update connector filtering
- Update connector name and description
- Update connector pipeline
- Update connector scheduling
- Update connector service type
- Create connector sync job
- Cancel connector sync job
- Delete connector sync job
- Get connector sync job
- List connector sync jobs
- Check in a connector
- Update connector error
- Update connector last sync stats
- Update connector status
- Check in connector sync job
- Claim connector sync job
- Set connector sync job error
- Set connector sync job stats
- Data stream APIs
- Document APIs
- Enrich APIs
- EQL APIs
- ES|QL APIs
- Features APIs
- Fleet APIs
- Graph explore API
- Index APIs
- Alias exists
- Aliases
- Analyze
- Analyze index disk usage
- Clear cache
- Clone index
- Close index
- Create index
- Create or update alias
- Create or update component template
- Create or update index template
- Create or update index template (legacy)
- Delete component template
- Delete dangling index
- Delete alias
- Delete index
- Delete index template
- Delete index template (legacy)
- Exists
- Field usage stats
- Flush
- Force merge
- Get alias
- Get component template
- Get field mapping
- Get index
- Get index settings
- Get index template
- Get index template (legacy)
- Get mapping
- Import dangling index
- Index recovery
- Index segments
- Index shard stores
- Index stats
- Index template exists (legacy)
- List dangling indices
- Open index
- Refresh
- Resolve index
- Resolve cluster
- Rollover
- Shrink index
- Simulate index
- Simulate template
- Split index
- Unfreeze index
- Update index settings
- Update mapping
- Index lifecycle management APIs
- Create or update lifecycle policy
- Get policy
- Delete policy
- Move to step
- Remove policy
- Retry policy
- Get index lifecycle management status
- Explain lifecycle
- Start index lifecycle management
- Stop index lifecycle management
- Migrate indices, ILM policies, and legacy, composable and component templates to data tiers routing
- Inference APIs
- Delete inference API
- Get inference API
- Perform inference API
- Create inference API
- Stream inference API
- Update inference API
- AlibabaCloud AI Search inference service
- Amazon Bedrock inference service
- Anthropic inference service
- Azure AI studio inference service
- Azure OpenAI inference service
- Cohere inference service
- Elasticsearch inference service
- ELSER inference service
- Google AI Studio inference service
- Google Vertex AI inference service
- HuggingFace inference service
- Mistral inference service
- OpenAI inference service
- Watsonx inference service
- Info API
- Ingest APIs
- Licensing APIs
- Logstash APIs
- Machine learning APIs
- Machine learning anomaly detection APIs
- Add events to calendar
- Add jobs to calendar
- Close jobs
- Create jobs
- Create calendars
- Create datafeeds
- Create filters
- Delete calendars
- Delete datafeeds
- Delete events from calendar
- Delete filters
- Delete forecasts
- Delete jobs
- Delete jobs from calendar
- Delete model snapshots
- Delete expired data
- Estimate model memory
- Flush jobs
- Forecast jobs
- Get buckets
- Get calendars
- Get categories
- Get datafeeds
- Get datafeed statistics
- Get influencers
- Get jobs
- Get job statistics
- Get model snapshots
- Get model snapshot upgrade statistics
- Get overall buckets
- Get scheduled events
- Get filters
- Get records
- Open jobs
- Post data to jobs
- Preview datafeeds
- Reset jobs
- Revert model snapshots
- Start datafeeds
- Stop datafeeds
- Update datafeeds
- Update filters
- Update jobs
- Update model snapshots
- Upgrade model snapshots
- Machine learning data frame analytics APIs
- Create data frame analytics jobs
- Delete data frame analytics jobs
- Evaluate data frame analytics
- Explain data frame analytics
- Get data frame analytics jobs
- Get data frame analytics jobs stats
- Preview data frame analytics
- Start data frame analytics jobs
- Stop data frame analytics jobs
- Update data frame analytics jobs
- Machine learning trained model APIs
- Clear trained model deployment cache
- Create or update trained model aliases
- Create part of a trained model
- Create trained models
- Create trained model vocabulary
- Delete trained model aliases
- Delete trained models
- Get trained models
- Get trained models stats
- Infer trained model
- Start trained model deployment
- Stop trained model deployment
- Update trained model deployment
- Migration APIs
- Node lifecycle APIs
- Query rules APIs
- Reload search analyzers API
- Repositories metering APIs
- Rollup APIs
- Root API
- Script APIs
- Search APIs
- Search Application APIs
- Searchable snapshots APIs
- Security APIs
- Authenticate
- Change passwords
- Clear cache
- Clear roles cache
- Clear privileges cache
- Clear API key cache
- Clear service account token caches
- Create API keys
- Create or update application privileges
- Create or update role mappings
- Create or update roles
- Bulk create or update roles API
- Bulk delete roles API
- Create or update users
- Create service account tokens
- Delegate PKI authentication
- Delete application privileges
- Delete role mappings
- Delete roles
- Delete service account token
- Delete users
- Disable users
- Enable users
- Enroll Kibana
- Enroll node
- Get API key information
- Get application privileges
- Get builtin privileges
- Get role mappings
- Get roles
- Query Role
- Get service accounts
- Get service account credentials
- Get Security settings
- Get token
- Get user privileges
- Get users
- Grant API keys
- Has privileges
- Invalidate API key
- Invalidate token
- OpenID Connect prepare authentication
- OpenID Connect authenticate
- OpenID Connect logout
- Query API key information
- Query User
- Update API key
- Update Security settings
- Bulk update API keys
- SAML prepare authentication
- SAML authenticate
- SAML logout
- SAML invalidate
- SAML complete logout
- SAML service provider metadata
- SSL certificate
- Activate user profile
- Disable user profile
- Enable user profile
- Get user profiles
- Suggest user profile
- Update user profile data
- Has privileges user profile
- Create Cross-Cluster API key
- Update Cross-Cluster API key
- Snapshot and restore APIs
- Snapshot lifecycle management APIs
- SQL APIs
- Synonyms APIs
- Text structure APIs
- Transform APIs
- Usage API
- Watcher APIs
- Definitions
- Command line tools
- elasticsearch-certgen
- elasticsearch-certutil
- elasticsearch-create-enrollment-token
- elasticsearch-croneval
- elasticsearch-keystore
- elasticsearch-node
- elasticsearch-reconfigure-node
- elasticsearch-reset-password
- elasticsearch-saml-metadata
- elasticsearch-service-tokens
- elasticsearch-setup-passwords
- elasticsearch-shard
- elasticsearch-syskeygen
- elasticsearch-users
- Optimizations
- Troubleshooting
- Fix common cluster issues
- Diagnose unassigned shards
- Add a missing tier to the system
- Allow Elasticsearch to allocate the data in the system
- Allow Elasticsearch to allocate the index
- Indices mix index allocation filters with data tiers node roles to move through data tiers
- Not enough nodes to allocate all shard replicas
- Total number of shards for an index on a single node exceeded
- Total number of shards per node has been reached
- Troubleshooting corruption
- Fix data nodes out of disk
- Fix master nodes out of disk
- Fix other role nodes out of disk
- Start index lifecycle management
- Start Snapshot Lifecycle Management
- Restore from snapshot
- Troubleshooting broken repositories
- Addressing repeated snapshot policy failures
- Troubleshooting an unstable cluster
- Troubleshooting discovery
- Troubleshooting monitoring
- Troubleshooting transforms
- Troubleshooting Watcher
- Troubleshooting searches
- Troubleshooting shards capacity health issues
- Troubleshooting an unbalanced cluster
- Capture diagnostics
- Migration guide
- Release notes
- Elasticsearch version 8.17.1
- Elasticsearch version 8.17.0
- Elasticsearch version 8.16.2
- Elasticsearch version 8.16.1
- Elasticsearch version 8.16.0
- Elasticsearch version 8.15.5
- Elasticsearch version 8.15.4
- Elasticsearch version 8.15.3
- Elasticsearch version 8.15.2
- Elasticsearch version 8.15.1
- Elasticsearch version 8.15.0
- Elasticsearch version 8.14.3
- Elasticsearch version 8.14.2
- Elasticsearch version 8.14.1
- Elasticsearch version 8.14.0
- Elasticsearch version 8.13.4
- Elasticsearch version 8.13.3
- Elasticsearch version 8.13.2
- Elasticsearch version 8.13.1
- Elasticsearch version 8.13.0
- Elasticsearch version 8.12.2
- Elasticsearch version 8.12.1
- Elasticsearch version 8.12.0
- Elasticsearch version 8.11.4
- Elasticsearch version 8.11.3
- Elasticsearch version 8.11.2
- Elasticsearch version 8.11.1
- Elasticsearch version 8.11.0
- Elasticsearch version 8.10.4
- Elasticsearch version 8.10.3
- Elasticsearch version 8.10.2
- Elasticsearch version 8.10.1
- Elasticsearch version 8.10.0
- Elasticsearch version 8.9.2
- Elasticsearch version 8.9.1
- Elasticsearch version 8.9.0
- Elasticsearch version 8.8.2
- Elasticsearch version 8.8.1
- Elasticsearch version 8.8.0
- Elasticsearch version 8.7.1
- Elasticsearch version 8.7.0
- Elasticsearch version 8.6.2
- Elasticsearch version 8.6.1
- Elasticsearch version 8.6.0
- Elasticsearch version 8.5.3
- Elasticsearch version 8.5.2
- Elasticsearch version 8.5.1
- Elasticsearch version 8.5.0
- Elasticsearch version 8.4.3
- Elasticsearch version 8.4.2
- Elasticsearch version 8.4.1
- Elasticsearch version 8.4.0
- Elasticsearch version 8.3.3
- Elasticsearch version 8.3.2
- Elasticsearch version 8.3.1
- Elasticsearch version 8.3.0
- Elasticsearch version 8.2.3
- Elasticsearch version 8.2.2
- Elasticsearch version 8.2.1
- Elasticsearch version 8.2.0
- Elasticsearch version 8.1.3
- Elasticsearch version 8.1.2
- Elasticsearch version 8.1.1
- Elasticsearch version 8.1.0
- Elasticsearch version 8.0.1
- Elasticsearch version 8.0.0
- Elasticsearch version 8.0.0-rc2
- Elasticsearch version 8.0.0-rc1
- Elasticsearch version 8.0.0-beta1
- Elasticsearch version 8.0.0-alpha2
- Elasticsearch version 8.0.0-alpha1
- Dependencies and versions
Retriever
editRetriever
editA retriever is a specification to describe top documents returned from a search.
A retriever replaces other elements of the search API
that also return top documents such as query
and
knn
.
A retriever may have child retrievers where a retriever with two or more children is considered a compound retriever.
This allows for complex behavior to be depicted in a tree-like structure, called the retriever tree, which clarifies the order of operations that occur during a search.
Refer to Retrievers for a high level overview of the retrievers abstraction. Refer to Retrievers examples for additional examples.
The following retrievers are available:
-
standard
- A retriever that replaces the functionality of a traditional query.
-
knn
- A retriever that replaces the functionality of a knn search.
-
rrf
- A retriever that produces top documents from reciprocal rank fusion (RRF).
-
text_similarity_reranker
- A retriever that enhances search results by re-ranking documents based on semantic similarity to a specified inference text, using a machine learning model.
-
rule
- A retriever that applies contextual Searching with query rules to pin or exclude documents for specific queries.
Standard Retriever
editA standard retriever returns top documents from a traditional query.
Parameters:
edit-
query
-
(Optional, query object)
Defines a query to retrieve a set of top documents.
-
filter
-
(Optional, query object or list of query objects)
Applies a boolean query filter to this retriever, where all documents must match this query but do not contribute to the score.
-
search_after
-
(Optional, search after object)
Defines a search after object parameter used for pagination.
-
terminate_after
-
(Optional, integer) Maximum number of documents to collect for each shard. If a query reaches this limit, Elasticsearch terminates the query early. Elasticsearch collects documents before sorting.
Use with caution. Elasticsearch applies this parameter to each shard handling the request. When possible, let Elasticsearch perform early termination automatically. Avoid specifying this parameter for requests that target data streams with backing indices across multiple data tiers.
-
sort
-
(Optional, sort object) A sort object that specifies the order of matching documents.
-
min_score
-
(Optional,
float
)Minimum
_score
for matching documents. Documents with a lower_score
are not included in the top documents. -
collapse
-
(Optional, collapse object)
Collapses the top documents by a specified key into a single top document per key.
Restrictions
editWhen a retriever tree contains a compound retriever (a retriever with two or more child retrievers) the search after parameter is not supported.
Example
editresp = client.search( index="restaurants", retriever={ "standard": { "query": { "bool": { "should": [ { "match": { "region": "Austria" } } ], "filter": [ { "term": { "year": "2019" } } ] } } } }, ) print(resp)
const response = await client.search({ index: "restaurants", retriever: { standard: { query: { bool: { should: [ { match: { region: "Austria", }, }, ], filter: [ { term: { year: "2019", }, }, ], }, }, }, }, }); console.log(response);
GET /restaurants/_search { "retriever": { "standard": { "query": { "bool": { "should": [ { "match": { "region": "Austria" } } ], "filter": [ { "term": { "year": "2019" } } ] } } } } }
Opens the |
|
The |
|
The entry point for defining the search query. |
|
The |
|
The |
|
The |
|
The |
|
The |
|
The exact value to match in the |
kNN Retriever
editA kNN retriever returns top documents from a k-nearest neighbor search (kNN).
Parameters
edit-
field
-
(Required, string)
The name of the vector field to search against. Must be a
dense_vector
field with indexing enabled. -
query_vector
-
(Required if
query_vector_builder
is not defined, array offloat
)Query vector. Must have the same number of dimensions as the vector field you are searching against. Must be either an array of floats or a hex-encoded byte vector.
-
query_vector_builder
-
(Required if
query_vector
is not defined, query vector builder object)Defines a model to build a query vector.
-
k
-
(Required, integer)
Number of nearest neighbors to return as top hits. This value must be fewer than or equal to
num_candidates
. -
num_candidates
-
(Required, integer)
The number of nearest neighbor candidates to consider per shard. Needs to be greater than
k
, orsize
ifk
is omitted, and cannot exceed 10,000. Elasticsearch collectsnum_candidates
results from each shard, then merges them to find the topk
results. Increasingnum_candidates
tends to improve the accuracy of the finalk
results. Defaults toMath.min(1.5 * k, 10_000)
. -
filter
-
(Optional, query object or list of query objects)
Query to filter the documents that can match. The kNN search will return the top
k
documents that also match this filter. The value can be a single query or a list of queries. Iffilter
is not provided, all documents are allowed to match. -
similarity
-
(Optional, float)
The minimum similarity required for a document to be considered a match. The similarity value calculated relates to the raw
similarity
used. Not the document score. The matched documents are then scored according tosimilarity
and the providedboost
is applied.The
similarity
parameter is the direct vector similarity calculation.-
l2_norm
: also known as Euclidean, will include documents where the vector is within thedims
dimensional hypersphere with radiussimilarity
with origin atquery_vector
. -
cosine
,dot_product
, andmax_inner_product
: Only return vectors where the cosine similarity or dot-product are at least the providedsimilarity
.
Read more here: knn similarity search
-
Restrictions
editThe parameters query_vector
and query_vector_builder
cannot be used together.
Example
editresp = client.search( index="restaurants", retriever={ "knn": { "field": "vector", "query_vector": [ 10, 22, 77 ], "k": 10, "num_candidates": 10 } }, ) print(resp)
const response = await client.search({ index: "restaurants", retriever: { knn: { field: "vector", query_vector: [10, 22, 77], k: 10, num_candidates: 10, }, }, }); console.log(response);
GET /restaurants/_search { "retriever": { "knn": { "field": "vector", "query_vector": [10, 22, 77], "k": 10, "num_candidates": 10 } } }
Configuration for k-nearest neighbor (knn) search, which is based on vector similarity. |
|
Specifies the field name that contains the vectors. |
|
The query vector against which document vectors are compared in the |
|
The number of nearest neighbors to return as top hits.
This value must be fewer than or equal to |
|
The size of the initial candidate set from which the final |
RRF Retriever
editAn RRF retriever returns top documents based on the RRF formula, equally weighting two or more child retrievers. Reciprocal rank fusion (RRF) is a method for combining multiple result sets with different relevance indicators into a single result set.
Parameters
edit-
retrievers
-
(Required, array of retriever objects)
A list of child retrievers to specify which sets of returned top documents will have the RRF formula applied to them. Each child retriever carries an equal weight as part of the RRF formula. Two or more child retrievers are required.
-
rank_constant
-
(Optional, integer)
This value determines how much influence documents in individual result sets per query have over the final ranked result set. A higher value indicates that lower ranked documents have more influence. This value must be greater than or equal to
1
. Defaults to60
. -
rank_window_size
-
(Optional, integer)
This value determines the size of the individual result sets per query. A higher value will improve result relevance at the cost of performance. The final ranked result set is pruned down to the search request’s size.
rank_window_size
must be greater than or equal tosize
and greater than or equal to1
. Defaults to thesize
parameter. -
filter
-
(Optional, query object or list of query objects)
Applies the specified boolean query filter to all of the specified sub-retrievers, according to each retriever’s specifications.
Example: Hybrid search
editA simple hybrid search example (lexical search + dense vector search) combining a standard
retriever with a knn
retriever using RRF:
resp = client.search( index="restaurants", retriever={ "rrf": { "retrievers": [ { "standard": { "query": { "multi_match": { "query": "Austria", "fields": [ "city", "region" ] } } } }, { "knn": { "field": "vector", "query_vector": [ 10, 22, 77 ], "k": 10, "num_candidates": 10 } } ], "rank_constant": 1, "rank_window_size": 50 } }, ) print(resp)
const response = await client.search({ index: "restaurants", retriever: { rrf: { retrievers: [ { standard: { query: { multi_match: { query: "Austria", fields: ["city", "region"], }, }, }, }, { knn: { field: "vector", query_vector: [10, 22, 77], k: 10, num_candidates: 10, }, }, ], rank_constant: 1, rank_window_size: 50, }, }, }); console.log(response);
GET /restaurants/_search { "retriever": { "rrf": { "retrievers": [ { "standard": { "query": { "multi_match": { "query": "Austria", "fields": [ "city", "region" ] } } } }, { "knn": { "field": "vector", "query_vector": [10, 22, 77], "k": 10, "num_candidates": 10 } } ], "rank_constant": 1, "rank_window_size": 50 } } }
Defines a retriever tree with an RRF retriever. |
|
The sub-retriever array. |
|
The first sub-retriever is a |
|
The second sub-retriever is a |
|
The rank constant for the RRF retriever. |
|
The rank window size for the RRF retriever. |
Example: Hybrid search with sparse vectors
editA more complex hybrid search example (lexical search + ELSER sparse vector search + dense vector search) using RRF:
resp = client.search( index="movies", retriever={ "rrf": { "retrievers": [ { "standard": { "query": { "sparse_vector": { "field": "plot_embedding", "inference_id": "my-elser-model", "query": "films that explore psychological depths" } } } }, { "standard": { "query": { "multi_match": { "query": "crime", "fields": [ "plot", "title" ] } } } }, { "knn": { "field": "vector", "query_vector": [ 10, 22, 77 ], "k": 10, "num_candidates": 10 } } ] } }, ) print(resp)
const response = await client.search({ index: "movies", retriever: { rrf: { retrievers: [ { standard: { query: { sparse_vector: { field: "plot_embedding", inference_id: "my-elser-model", query: "films that explore psychological depths", }, }, }, }, { standard: { query: { multi_match: { query: "crime", fields: ["plot", "title"], }, }, }, }, { knn: { field: "vector", query_vector: [10, 22, 77], k: 10, num_candidates: 10, }, }, ], }, }, }); console.log(response);
GET movies/_search { "retriever": { "rrf": { "retrievers": [ { "standard": { "query": { "sparse_vector": { "field": "plot_embedding", "inference_id": "my-elser-model", "query": "films that explore psychological depths" } } } }, { "standard": { "query": { "multi_match": { "query": "crime", "fields": [ "plot", "title" ] } } } }, { "knn": { "field": "vector", "query_vector": [10, 22, 77], "k": 10, "num_candidates": 10 } } ] } } }
Text Similarity Re-ranker Retriever
editThe text_similarity_reranker
retriever uses an NLP model to improve search results by reordering the top-k documents based on their semantic similarity to the query.
Refer to Semantic re-ranking for a high level overview of semantic re-ranking.
Prerequisites
editTo use text_similarity_reranker
you must first set up an inference endpoint for the rerank
task using the Create inference API.
The endpoint should be set up with a machine learning model that can compute text similarity.
Refer to the Elastic NLP model reference for a list of third-party text similarity models supported by Elasticsearch.
You have the following options:
- Use the the built-in Elastic Rerank cross-encoder model via the inference API’s Elasticsearch service.
-
Use the Cohere Rerank inference endpoint with the
rerank
task type. -
Use the Google Vertex AI inference endpoint with the
rerank
task type. -
Upload a model to Elasticsearch with Eland using the
text_similarity
NLP task type.-
Then set up an Elasticsearch service inference endpoint with the
rerank
task type. - Refer to the example on this page for a step-by-step guide.
-
Then set up an Elasticsearch service inference endpoint with the
Parameters
edit-
retriever
-
(Required, retriever)
The child retriever that generates the initial set of top documents to be re-ranked.
-
field
-
(Required,
string
)The document field to be used for text similarity comparisons. This field should contain the text that will be evaluated against the
inferenceText
. -
inference_id
-
(Required,
string
)Unique identifier of the inference endpoint created using the inference API.
-
inference_text
-
(Required,
string
)The text snippet used as the basis for similarity comparison.
-
rank_window_size
-
(Optional,
int
)The number of top documents to consider in the re-ranking process. Defaults to
10
. -
min_score
-
(Optional,
float
)Sets a minimum threshold score for including documents in the re-ranked results. Documents with similarity scores below this threshold will be excluded. Note that score calculations vary depending on the model used.
-
filter
-
(Optional, query object or list of query objects)
Applies the specified boolean query filter to the child retriever. If the child retriever already specifies any filters, then this top-level filter is applied in conjuction with the filter defined in the child retriever.
Example: Elastic Rerank
editThis examples demonstrates how to deploy the Elastic Rerank model and use it to re-rank search results using the text_similarity_reranker
retriever.
Follow these steps:
-
Create an inference endpoint for the
rerank
task using the Create inference API.resp = client.inference.put( task_type="rerank", inference_id="my-elastic-rerank", inference_config={ "service": "elasticsearch", "service_settings": { "model_id": ".rerank-v1", "num_threads": 1, "adaptive_allocations": { "enabled": True, "min_number_of_allocations": 1, "max_number_of_allocations": 10 } } }, ) print(resp)
const response = await client.inference.put({ task_type: "rerank", inference_id: "my-elastic-rerank", inference_config: { service: "elasticsearch", service_settings: { model_id: ".rerank-v1", num_threads: 1, adaptive_allocations: { enabled: true, min_number_of_allocations: 1, max_number_of_allocations: 10, }, }, }, }); console.log(response);
PUT _inference/rerank/my-elastic-rerank { "service": "elasticsearch", "service_settings": { "model_id": ".rerank-v1", "num_threads": 1, "adaptive_allocations": { "enabled": true, "min_number_of_allocations": 1, "max_number_of_allocations": 10 } } }
Adaptive allocations will be enabled with the minimum of 1 and the maximum of 10 allocations.
-
Define a
text_similarity_rerank
retriever:resp = client.search( retriever={ "text_similarity_reranker": { "retriever": { "standard": { "query": { "match": { "text": "How often does the moon hide the sun?" } } } }, "field": "text", "inference_id": "my-elastic-rerank", "inference_text": "How often does the moon hide the sun?", "rank_window_size": 100, "min_score": 0.5 } }, ) print(resp)
const response = await client.search({ retriever: { text_similarity_reranker: { retriever: { standard: { query: { match: { text: "How often does the moon hide the sun?", }, }, }, }, field: "text", inference_id: "my-elastic-rerank", inference_text: "How often does the moon hide the sun?", rank_window_size: 100, min_score: 0.5, }, }, }); console.log(response);
POST _search { "retriever": { "text_similarity_reranker": { "retriever": { "standard": { "query": { "match": { "text": "How often does the moon hide the sun?" } } } }, "field": "text", "inference_id": "my-elastic-rerank", "inference_text": "How often does the moon hide the sun?", "rank_window_size": 100, "min_score": 0.5 } } }
Example: Cohere Rerank
editThis example enables out-of-the-box semantic search by re-ranking top documents using the Cohere Rerank API.
This approach eliminates the need to generate and store embeddings for all indexed documents.
This requires a Cohere Rerank inference endpoint that is set up for the rerank
task type.
resp = client.search( index="index", retriever={ "text_similarity_reranker": { "retriever": { "standard": { "query": { "match_phrase": { "text": "landmark in Paris" } } } }, "field": "text", "inference_id": "my-cohere-rerank-model", "inference_text": "Most famous landmark in Paris", "rank_window_size": 100, "min_score": 0.5 } }, ) print(resp)
const response = await client.search({ index: "index", retriever: { text_similarity_reranker: { retriever: { standard: { query: { match_phrase: { text: "landmark in Paris", }, }, }, }, field: "text", inference_id: "my-cohere-rerank-model", inference_text: "Most famous landmark in Paris", rank_window_size: 100, min_score: 0.5, }, }, }); console.log(response);
GET /index/_search { "retriever": { "text_similarity_reranker": { "retriever": { "standard": { "query": { "match_phrase": { "text": "landmark in Paris" } } } }, "field": "text", "inference_id": "my-cohere-rerank-model", "inference_text": "Most famous landmark in Paris", "rank_window_size": 100, "min_score": 0.5 } } }
Example: Semantic re-ranking with a Hugging Face model
editThe following example uses the cross-encoder/ms-marco-MiniLM-L-6-v2
model from Hugging Face to rerank search results based on semantic similarity.
The model must be uploaded to Elasticsearch using Eland.
Refer to the Elastic NLP model reference for a list of third party text similarity models supported by Elasticsearch.
Follow these steps to load the model and create a semantic re-ranker.
-
Install Eland using
pip
python -m pip install eland[pytorch]
-
Upload the model to Elasticsearch using Eland. This example assumes you have an Elastic Cloud deployment and an API key. Refer to the Eland documentation for more authentication options.
eland_import_hub_model \ --cloud-id $CLOUD_ID \ --es-api-key $ES_API_KEY \ --hub-model-id cross-encoder/ms-marco-MiniLM-L-6-v2 \ --task-type text_similarity \ --clear-previous \ --start
-
Create an inference endpoint for the
rerank
taskresp = client.inference.put( task_type="rerank", inference_id="my-msmarco-minilm-model", inference_config={ "service": "elasticsearch", "service_settings": { "num_allocations": 1, "num_threads": 1, "model_id": "cross-encoder__ms-marco-minilm-l-6-v2" } }, ) print(resp)
const response = await client.inference.put({ task_type: "rerank", inference_id: "my-msmarco-minilm-model", inference_config: { service: "elasticsearch", service_settings: { num_allocations: 1, num_threads: 1, model_id: "cross-encoder__ms-marco-minilm-l-6-v2", }, }, }); console.log(response);
PUT _inference/rerank/my-msmarco-minilm-model { "service": "elasticsearch", "service_settings": { "num_allocations": 1, "num_threads": 1, "model_id": "cross-encoder__ms-marco-minilm-l-6-v2" } }
-
Define a
text_similarity_rerank
retriever.resp = client.search( index="movies", retriever={ "text_similarity_reranker": { "retriever": { "standard": { "query": { "match": { "genre": "drama" } } } }, "field": "plot", "inference_id": "my-msmarco-minilm-model", "inference_text": "films that explore psychological depths" } }, ) print(resp)
const response = await client.search({ index: "movies", retriever: { text_similarity_reranker: { retriever: { standard: { query: { match: { genre: "drama", }, }, }, }, field: "plot", inference_id: "my-msmarco-minilm-model", inference_text: "films that explore psychological depths", }, }, }); console.log(response);
POST movies/_search { "retriever": { "text_similarity_reranker": { "retriever": { "standard": { "query": { "match": { "genre": "drama" } } } }, "field": "plot", "inference_id": "my-msmarco-minilm-model", "inference_text": "films that explore psychological depths" } } }
This retriever uses a standard
match
query to search themovie
index for films tagged with the genre "drama". It then re-ranks the results based on semantic similarity to the text in theinference_text
parameter, using the model we uploaded to Elasticsearch.
Query Rules Retriever
editThe rule
retriever enables fine-grained control over search results by applying contextual query rules to pin or exclude documents for specific queries.
This retriever has similar functionality to the rule query, but works out of the box with other retrievers.
Prerequisites
editTo use the rule
retriever you must first create one or more query rulesets using the query rules management APIs.
Parameters
edit-
retriever
-
(Required, retriever)
The child retriever that returns the results to apply query rules on top of. This can be a standalone retriever such as the standard or knn retriever, or it can be a compound retriever.
-
ruleset_ids
-
(Required,
array
)An array of one or more unique query ruleset IDs with query-based rules to match and apply as applicable. Rulesets and their associated rules are evaluated in the order in which they are specified in the query and ruleset. The maximum number of rulesets to specify is 10.
-
match_criteria
-
(Required,
object
)Defines the match criteria to apply to rules in the given query ruleset(s). Match criteria should match the keys defined in the
criteria.metadata
field of the rule. -
rank_window_size
-
(Optional,
int
)The number of top documents to return from the
rule
retriever. Defaults to10
.
Example: Rule retriever
editThis example shows the rule retriever executed without any additional retrievers.
It runs the query defined by the retriever
and applies the rules from my-ruleset
on top of the returned results.
resp = client.search( index="movies", retriever={ "rule": { "match_criteria": { "query_string": "harry potter" }, "ruleset_ids": [ "my-ruleset" ], "retriever": { "standard": { "query": { "query_string": { "query": "harry potter" } } } } } }, ) print(resp)
const response = await client.search({ index: "movies", retriever: { rule: { match_criteria: { query_string: "harry potter", }, ruleset_ids: ["my-ruleset"], retriever: { standard: { query: { query_string: { query: "harry potter", }, }, }, }, }, }, }); console.log(response);
GET movies/_search { "retriever": { "rule": { "match_criteria": { "query_string": "harry potter" }, "ruleset_ids": [ "my-ruleset" ], "retriever": { "standard": { "query": { "query_string": { "query": "harry potter" } } } } } } }
Example: Rule retriever combined with RRF
editThis example shows how to combine the rule
retriever with other rerank retrievers such as rrf or text_similarity_reranker.
The rule
retriever will apply rules to any documents returned from its defined retriever
or any of its sub-retrievers.
This means that for the best results, the rule
retriever should be the outermost defined retriever.
Nesting a rule
retriever as a sub-retriever under a reranker such as rrf
or text_similarity_reranker
may not produce the expected results.
resp = client.search( index="movies", retriever={ "rule": { "match_criteria": { "query_string": "harry potter" }, "ruleset_ids": [ "my-ruleset" ], "retriever": { "rrf": { "retrievers": [ { "standard": { "query": { "query_string": { "query": "sorcerer's stone" } } } }, { "standard": { "query": { "query_string": { "query": "chamber of secrets" } } } } ] } } } }, ) print(resp)
const response = await client.search({ index: "movies", retriever: { rule: { match_criteria: { query_string: "harry potter", }, ruleset_ids: ["my-ruleset"], retriever: { rrf: { retrievers: [ { standard: { query: { query_string: { query: "sorcerer's stone", }, }, }, }, { standard: { query: { query_string: { query: "chamber of secrets", }, }, }, }, ], }, }, }, }, }); console.log(response);
GET movies/_search { "retriever": { "rule": { "match_criteria": { "query_string": "harry potter" }, "ruleset_ids": [ "my-ruleset" ], "retriever": { "rrf": { "retrievers": [ { "standard": { "query": { "query_string": { "query": "sorcerer's stone" } } } }, { "standard": { "query": { "query_string": { "query": "chamber of secrets" } } } } ] } } } } }
The |
|
The |
Common usage guidelines
editUsing from
and size
with a retriever tree
editThe from
and size
parameters are provided globally as part of the general
search API.
They are applied to all retrievers in a retriever tree, unless a specific retriever overrides the size
parameter using a different parameter such as rank_window_size
.
Though, the final search hits are always limited to size
.
Using aggregations with a retriever tree
editAggregations are globally specified as part of a search request.
The query used for an aggregation is the combination of all leaf retrievers as should
clauses in a boolean query.
Restrictions on search parameters when specifying a retriever
editWhen a retriever is specified as part of a search, the following elements are not allowed at the top-level:
On this page
- Standard Retriever
- Parameters:
- Restrictions
- Example
- kNN Retriever
- Parameters
- Restrictions
- Example
- RRF Retriever
- Parameters
- Example: Hybrid search
- Example: Hybrid search with sparse vectors
- Text Similarity Re-ranker Retriever
- Prerequisites
- Parameters
- Example: Elastic Rerank
- Example: Cohere Rerank
- Example: Semantic re-ranking with a Hugging Face model
- Query Rules Retriever
- Prerequisites
- Parameters
- Example: Rule retriever
- Example: Rule retriever combined with RRF
- Common usage guidelines
- Using
from
andsize
with a retriever tree - Using aggregations with a retriever tree
- Restrictions on search parameters when specifying a retriever