Hybrid search combines the advantages of vector search and traditional text search. You can flexibly select suitable combinations based on business scenarios to deliver more precise search results that meet specific recall requirements.
Pre-Filtering
Search method: Filters are applied prior to vector search. Vector similarity calculation is only performed on documents that meet the conditions.
Scenarios: Suitable for scenarios with clear filtering conditions, such as book category filtering and e-commerce product category filtering.
GET book-index/_search
{
"knn":{
"field":"title_vector",
"query_vector": [0.1, 0.2, 0.3 ...],
"k":10,
"num_candidates": 100,
"filter":{
"term":{
"category": "History"
}
}
}
}
Post-Filtering
Search method: Vector search is executed first, followed by filtering on the results.
Scenarios: Suitable for scenarios that require a broad search first, followed by filtering to narrow down the results.
Note: Post-filtering may filter out a large number of results, leading to an insufficient number of returned documents. Therefore, it is recommended to set a larger k value to ensure that enough results are returned.
In the following sample code, the execution effect is the same whether the filter clause is placed before or after the must clause. In both cases, post-filtering is applied.
GET book-index/_search
{
"query":{
"bool":{
"must":[
{
"knn":{
"field":"content_vector",
"query_vector": [0.1, 0.2, 0.3 ...],
"k":100,
"num_candidates": 500
}
}
],
"filter":[
{
"range": {
"price": {
"gte": 15,
"lte": 25
}
}
}
]
}
},
"size": 10
}
Parallel Search
Search method: Vector search and text search are executed in parallel. Their results are merged by score, and the weights can be adjusted using boost.
Scenarios: Suitable for scenarios where both semantic similarity and keyword matching are equally important.
GET book-index/_search
{
"query":{
"bool":{
"should":[
{
"range": {
"price": {
"gte": 15,
"lte": 25
}
}
},
{
"knn":{
"field":"title_vector",
"query_vector": [0.1, 0.2, 0.3 ...],
"k":2,
"num_candidates": 50
}
}
]
}
}
}