Hybrid full-text and vector search
Hybrid search combines full-text search and vector search. Compared to using only one of these methods, hybrid search often returns more precise and relevant results. This topic describes how to use the hybrid full-text and vector search feature of the Lindorm vector engine.
Prerequisites
A Java environment is installed. JDK 1.8 or later is required.
The vector engine is activated. For information about how to activate the vector engine, see Activate the vector engine.
The search engine is activated. For information about how to activate the search engine, see Activation guide.
The IP address of your client is added to the allowlist of your Lindorm instance. For more information, see Configure a whitelist.
Preparations
Before you use advanced features, you must install the Java High Level REST Client and connect to the search engine. For more information, see Preparations.
Dual-channel full-text and vector retrieval (RRF hybrid search)
In some query scenarios, you may need to combine results from both full-text and vector indexes. The results from each index are then weighted based on a scoring rule to determine the final ranking.
Create an index
The following example uses the Hierarchical Navigable Small World (HNSW) algorithm.
If you use the IVFPQ algorithm, you must first set knn.offline.construction to true, import offline data, and then start index construction. You can perform queries only after the index construction is complete. For more information, see Create a vector index and Index construction.
String indexName = "vector_text_hybridSearch";
int dim = 3;
CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
createIndexRequest.settings(Map.of(
"index", Map.of(
"number_of_shards", 2,
"knn", true)));
createIndexRequest.mapping(Map.of(
"_source", Map.of(
"excludes", new String[] { "vector1" }
),
"properties", Map.of(
"vector1", Map.of(
"type", "knn_vector",
"dimension", dim,
"method", Map.of(
"engine", "lvector",
"name", "hnsw",
"space_type", "l2",
"parameters", Map.of(
"m", 24,
"ef_construction", 500
)
)
),
"text_field", Map.of(
"type", "text",
"analyzer", "ik_max_word"
),
"field1", Map.of(
"type", "long"
)
)
));
CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
System.out.println("createIndexResponse: " + createIndexResponse.index());Ingest data
// Prepare a batch request.
String index = "vector_text_hybridSearch";
BulkRequest bulkRequest = new BulkRequest();
// Add multiple IndexRequest objects. Each object represents a document.
bulkRequest.add(new IndexRequest(index).id("1").source(Map.of(
"field1", 1, "field2", "flag1", "vector1", new float[]{2.5f, 2.3f, 2.4f}, "text_field", "hello test5")));
bulkRequest.add(new IndexRequest(index).id("2").source(Map.of(
"field1", 2, "field2", "flag1", "vector1", new float[]{2.6f, 2.3f, 2.4f}, "text_field", "hello test6 test5")));
bulkRequest.add(new IndexRequest(index).id("3").source(Map.of(
"field1", 3, "field2", "flag1", "vector1", new float[]{2.7f, 2.3f, 2.4f}, "text_field", "hello test7")));
bulkRequest.add(new IndexRequest(index).id("4").source(Map.of(
"field1", 4, "field2", "flag2", "vector1", new float[]{2.8f, 2.3f, 2.4f}, "text_field", "hello test8 test7")));
bulkRequest.add(new IndexRequest(index).id("5").source(Map.of(
"field1", 5, "field2", "flag2", "vector1", new float[]{2.9f, 2.3f, 2.4f}, "text_field", "hello test9")));
bulkRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
if (bulkResponse.hasFailures()) {
// Handle potential failures.
System.out.println("Bulk operation had failures:");
System.out.println(bulkResponse.buildFailureMessage());
} else {
System.out.println("Bulk operation completed successfully.");
}Query data (hybrid search)
The Reciprocal Rank Fusion (RRF) calculation is as follows:
When you perform a query, the system retrieves the topK results from the full-text search and the vector search. The system then calculates a score for each returned document ID using the RRF formula: 1/(rrf_rank_constant + rank(i)). In this formula, rrf_rank_constant is a configurable parameter and `rank(i)` is the rank of the document in the result set.
If a document ID appears in the top K results of both the full-text search and the vector search, its final score is the sum of its scores from both search methods. If a document ID appears in the results of only one search method, its final score is the score from that method.
For example, if rrf_rank_constant = 1, the results are calculated as follows:
# doc | queryA | queryB | score
_id: 1 = 1.0/(1+1) + 0 = 0.5
_id: 2 = 1.0/(1+2) + 0 = 0.33
_id: 4 = 0 + 1.0/(1+2) = 0.33
_id: 5 = 0 + 1.0/(1+1) = 0.5You can perform hybrid queries using the _search interface or the _msearch_rrf interface. The following table compares the two interfaces.
Interface | Open source | Readability | Can I adjust the ratio between full-text search and vector search? |
_search | Compatible | Difficult to read | Support |
_msearch_rrf | Proprietary | Easy to read | No |
The following examples show how to use the _search and _msearch_rrf interfaces in two scenarios:
Scenario without scalar field filtering
Use the open source _search interface
Pros: It is compatible with the open source _search interface and lets you adjust the weight ratio between the full-text search and the vector search using the rrf_knn_weight_factor parameter.
Cons: The syntax is complex.
If you do not set the filter_type parameter in the ext.lvector extension field, the RRF search includes only the full-text search and the vector search. Scalar field filtering is not performed during the vector search.
SearchRequest searchRequest = new SearchRequest();
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
Map<String, Object> queryBody = Map.of(
"knn", Map.of(
"vector1", Map.of(
"vector", new float[]{2.8f, 2.3f, 2.4f},
"filter", Map.of(
"match", Map.of(
"text_field", "test5 test6 test7 test8 test9"
)
),
"k", 10
)
));
searchSourceBuilder.query(QueryBuilders.wrapperQuery(new Gson().toJson(queryBody)));
Map<String, String> ext = Map.of(
"hybrid_search_type", "filter_rrf",
"rrf_rank_constant", "60",
"rrf_knn_weight_factor", "0.5");
searchSourceBuilder.ext(Collections.singletonList(new LVectorExtBuilder("lvector", ext)));
// Configure the _source interface to include properties in the return value.
searchSourceBuilder.fetchSource(new FetchSourceContext(true));
searchRequest.source(searchSourceBuilder);
searchRequest.indices(index);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(searchResponse);For the definition of the LVectorExtBuilder class, see LVectorExtBuilder.
Use the proprietary _msearch_rrf interface
Pros: The syntax is clearer.
Cons: It is not compatible with the open source _search interface and does not support adjusting the weight ratio between the full-text search and the vector search.
Request searchRequest = new Request("GET", "/_msearch_rrf?re_score=true&rrf_rank_constant=60&pretty");
String jsonString = """
{"index": "vector_text_hybridSearch"}
{"size":10,"_source":false, "query":{"match":{"text_field":"test5 test6 test7 test8 test9"}}}
{"index": "vector_text_hybridSearch"}
{"size":10,"_source":false,"query":{"knn":{"vector1":{"vector":[2.8,2.3,2.4],"k":10}}}}
""";
searchRequest.setJsonEntity(jsonString);
Response response = client.getLowLevelClient().performRequest(searchRequest);
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println("msearchRrf responseBody = " + responseBody);You must add re_score=true to the connection parameters.
Scenario with scalar field filtering
Use the open source _search interface
You can set the filter_type parameter in the ext.lvector extension field to specify that the vector search component of the RRF search also requires scalar field filtering.
For an RRF-based hybrid search with a filter condition, you must place the full-text search query condition and the filter condition into two separate bool expressions connected by bool.must. The first bool expression in must is used for the full-text search to calculate the full-text match score. The second bool filter expression is used as the filter condition for the k-nearest neighbor (k-NN) search.
String index = "vector_text_hybridSearch";
SearchRequest searchRequest = new SearchRequest();
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
Map<String, Object> queryBody = Map.of(
"knn", Map.of(
"vector1", Map.of(
"vector", List.of(2.8, 2.3, 2.4),
"filter", Map.of(
"bool", Map.of(
"must", List.of(
Map.of(
"bool", Map.of(
"must", List.of(
Map.of(
"match", Map.of(
"text_field", Map.of(
"query", "test5 test6 test7 test8 test9"
)
)
)
)
)
),
Map.of(
"bool", Map.of(
"filter", List.of(
Map.of(
"range", Map.of(
"field1", Map.of(
"gt", 2
)
)
)
)
)
)
)
)
),
"k", 10
)
)
);
searchSourceBuilder.query(QueryBuilders.wrapperQuery(new Gson().toJson(queryBody)));
Map<String, String> ext = Map.of(
"filter_type", "efficient_filter",
"hybrid_search_type", "filter_rrf",
"rrf_rank_constant", "60",
"rrf_knn_weight_factor", "0.5");
searchSourceBuilder.ext(Collections.singletonList(new LVectorExtBuilder("lvector", ext)));
// Configure the _source interface to include properties in the return value.
searchSourceBuilder.fetchSource(new FetchSourceContext(true));
searchRequest.source(searchSourceBuilder);
searchRequest.indices(index);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(searchResponse);For the definition of the LVectorExtBuilder class, see LVectorExtBuilder.
Use the proprietary _msearch_rrf interface
The proprietary _msearch_rrf interface can be called only using the Java Low Level REST Client. For more information, see Scenario with scalar field filtering.