Write and query data with automatic embedding
Automatic embedding uses built-in pre-trained models to automatically convert text into vectors. This simplifies the process by eliminating the need to manually define vector fields. This topic describes how to use the Java High Level REST Client to write and query data with automatic embedding in the Lindorm vector engine.
Prerequisites
A Java environment is installed. JDK 1.8 or later is required.
-
The vector engine must be enabled. For instructions, see Enable vector engine.
-
The search engine must be enabled, and its version must be 3.11.16 or later. To enable the engine, see the Activation guide. To view or upgrade your current version, see Search engine version information and Upgrade a minor version.
ImportantIf your search engine version is earlier than 3.11.16 but the console indicates that it is the latest version, contact Lindorm technical support (DingTalk ID: s0s3eg3).
-
The AI engine must be enabled. For instructions, see the Activation guide. If you need to use Alibaba Cloud Model Studio models, select the Dashscope model option during activation. If this option is not available, contact Lindorm technical support (DingTalk ID: s0s3eg3).
Note-
The AI engine depends on the wide table engine, which must also be enabled.
-
-
Your client IP address must be added to the Lindorm whitelist. For instructions, see Configure a whitelist.
Notes
The JSON strings in the code examples use text blocks (""" """), a feature available in JDK 15 and later. If you use an earlier JDK version, you must convert these blocks into concatenated multi-line strings.
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.
Procedure overview
Procedure | Engine involved | Description |
AI engine | Call the RESTful API of the AI engine using a curl command to deploy the BGE-M3 embedding model. This model is used to convert text data into vectors. | |
Search engine | Create a write pipeline in the search engine to automatically convert text data into vector data (embedding) when you write data. | |
Search engine | Create a query pipeline in the search engine to automatically convert text data into vector data when you query data. | |
Vector engine, Search engine | When you create or modify a vector index, specify the write and query pipelines. These pipelines automatically convert written and queried data into vector data. | |
Vector engine, Search engine | Use the specified write pipeline to automatically convert the written text data into vector data. | |
Vector engine, Search engine | Use the specified query pipeline to automatically convert the queried text data into vector data. |
Deploy embedding model (Optional)
For instructions on deploying models in the AI engine, see Model Management and Examples of Using the AI engine RESTful API with curl commands.
The following example shows how to deploy the BGE_VISUALIZED model. For parameter details, see Model Management.
Use the AI engine's private network endpoint as the URL for your curl request.
curl -i -k --location --header 'x-ld-ak:<username>' --header 'x-ld-sk:<password>' -X POST http://<URL>/v1/ai/models/create -H "Content-Type: application/json" -d '{
"model_name": "bge_visualized_model",
"model_path": "huggingface://BAAI/bge-visualized",
"task": "FEATURE_EXTRACTION",
"algorithm": "BGE_VISUALIZED_M3",
"settings": {"instance_count": "2"}
}'
Create a search engine pipeline
You can create two types of pipelines in the search engine. These pipelines enable automatic vectorization during data writing and querying.
Create a write pipeline
String pipelineId = "write_embedding_pipeline";
String pipelineDefinition = """
{
"description": "demo_chunking pipeline",
"processors": [
{
"text-embedding": {
"inputFields": ["text_field"],
"outputFields": ["text_field_embedding"],
"userName": "user", // The username of the AI engine
"password": "test****", // The password of the AI engine
"url": "http://ld-t4n5668xk31ui****-proxy-ai-vpc.lindorm.aliyuncs.com:9002", // The private endpoint of the AI engine
"modeName": "bge_m3_model"
}
}
]
}
""";
BytesArray source = new BytesArray(pipelineDefinition.getBytes(StandardCharsets.UTF_8));
PutPipelineRequest request = new PutPipelineRequest(pipelineId, source, XContentType.JSON);
AcknowledgedResponse response = client.ingest().putPipeline(request, RequestOptions.DEFAULT);
System.out.println("CreatePipeline Acknowledged: " + response.isAcknowledged());Parameter description
Parameter | Description |
processors | Performs a pipeline operation on the written data. |
text-embedding | A fixed key. This parameter is required. |
inputFields | The text field that needs to be vectorized. |
outputFields | The vector field after vectorization. |
userName | The username for the Lindorm AI engine. |
password | The password for the Lindorm AI engine. |
url | The endpoint of the AI engine. You must use the private endpoint. |
modeName | The model name. In this topic, the value is |
The inputFields and outputFields specified in the write and query pipelines must be the same as the text_field and text_field_embedding specified when you create the vector index.
Create a query pipeline
String jsonString = """
{
"request_processors": [
{
"text-embedding" : {
"tag" : "auto-query-embedding",
"description" : "Auto query embedding",
"model_config" : {
"inputFields": ["text_field"],
"outputFields": ["text_field_embedding"],
"userName": "user", // The username of the AI engine
"password": "test****", // The password of the AI engine
"url": "http://ld-t4n5668xk31ui****-proxy-ai-vpc.lindorm.aliyuncs.com:9002", // The private endpoint of the AI engine
"modeName": "bge_m3_model"
}
}
}
]
}
""";
String pipelineName = "knnsearch_pipeline";
Request createPipelineRequest = new Request("PUT", "/_search/pipeline/" + pipelineName);
createPipelineRequest.setJsonEntity(jsonString);
Response response = client.getLowLevelClient().performRequest(createPipelineRequest);
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println("create knnSearch Pipeline responseBody = " + responseBody);Parameter description
Parameter | Description |
request_processors | Performs a pipeline operation on the search request. |
text-embedding | A fixed key. This parameter is required. |
inputFields | The text field that needs to be vectorized. It serves as a placeholder. |
outputFields | The vector field after vectorization. |
userName | The username for the Lindorm AI engine. |
password | The password for the Lindorm AI engine. |
url | The endpoint of the AI engine. You must use the private endpoint. |
modeName | The model name. In this topic, the value is |
The inputFields and outputFields specified in the ingest pipeline must match the input_field and embedding_field specified when you create the vector index.
Create an index and specify pipelines
When you create a vector index or modify the settings of an existing vector index, you must specify the required pipelines.
Create a vector index
String indexName = "search_vector_test";
CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
createIndexRequest.settings(Map.of(
"index", Map.of(
"number_of_shards", 2,
"knn", true,
"default_pipeline", "write_embedding_pipeline",
"search.default_pipeline", "knnsearch_pipeline")));
createIndexRequest.mapping(Map.of(
"_source", Map.of("excludes", new String[] {"text_field_embedding"}),
"properties", Map.of(
"text_field", Map.of(
"type", "text",
"analyzer", "ik_max_word"
),
"text_field_embedding", Map.of(
"type", "knn_vector",
"dimension", 1024,
"method", Map.of(
"engine", "lvector",
"name", "hnsw",
"space_type", "cosinesimil",
"parameters", Map.of(
"m", 24,
"ef_construction", 500
)
)
),
"tag", Map.of(
"type", "keyword"
),
"brand", Map.of(
"type", "keyword"
),
"merit", Map.of(
"type", "text",
"analyzer", "ik_max_word"
)
)
));
CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
System.out.println("createIndexResponse: " + createIndexResponse.index());Modify the settings of an existing vector index
If you have already created a vector index, you can modify its configuration to specify the pipelines for writing and querying data. This lets you meet your specific business requirements.
String indexName = "search_vector_test";
String jsonString = """
{
"index": {
"default_pipeline": "write_embedding_pipeline",
"search.default_pipeline": "knnsearch_pipeline"
}
}
""";
UpdateSettingsRequest updateSettingsRequest = new UpdateSettingsRequest(indexName).settings(jsonString, XContentType.JSON);
AcknowledgedResponse response = client.indices().putSettings(updateSettingsRequest, RequestOptions.DEFAULT);
System.out.println("updateIndexSettings Acknowledged: " + response.isAcknowledged());Write data
Because a write pipeline is specified, you only need to write data to the text_field. The pipeline automatically encodes the data in the text_field into a vector and writes the vector to the text_field_embedding field.
BulkRequest bulkRequest = new BulkRequest();
// Adding multiple IndexRequest to BulkRequest
bulkRequest.add(new IndexRequest("search_vector_test").id("3982")
.source(XContentType.JSON,
"text_field", "Brand A stylish energy-saving wireless mouse (grass green) (Glare. Rhythm. Stylish dancing mouse 12-month battery life High-precision optical tracking engine Ultra-fine receiver with 10-meter transmission distance)",
"tag", new String[] {"Mouse", "Electronic products"},
"brand", "Brand A",
"merit", "Easy to use, attractive appearance"));
bulkRequest.add(new IndexRequest("search_vector_test").id("323519")
.source(XContentType.JSON,
"text_field", "Brand B optical mouse (classic black) (Smart auto-pairing/1000 DPI high-precision optical engine)",
"tag", new String[] {"Mouse", "Electronic products"},
"brand", "Brand B",
"merit", "Good quality, fast delivery, attractive appearance, easy to use"));
bulkRequest.add(new IndexRequest("search_vector_test").id("300265")
.source(XContentType.JSON,
"text_field", "Brand C in-ear headphones white (classic and stylish)",
"tag", new String[] {"Headphones", "Electronic products"},
"brand", "Brand C",
"merit", "Attractive appearance, good quality"));
bulkRequest.add(new IndexRequest("search_vector_test").id("6797")
.source(XContentType.JSON,
"text_field", "Brand D two-head rechargeable electric shaver",
"tag", new String[] {"Home appliances", "Electric shaver"},
"brand", "Brand D",
"merit", "Easy to use, attractive appearance"));
bulkRequest.add(new IndexRequest("search_vector_test").id("8195")
.source(XContentType.JSON,
"text_field", "Brand E Class4 32G TF card (micro SD) mobile phone storage card",
"tag", new String[] {"Storage device", "Storage card", "SD card"},
"brand", "Brand E",
"merit", "Large capacity, fast speed, easy to use, good quality"));
bulkRequest.add(new IndexRequest("search_vector_test").id("13316")
.source(XContentType.JSON,
"text_field", "Brand E 101 G2 32GB USB flash drive",
"tag", new String[] {"Storage device", "USB drive", "USB flash drive"},
"brand", "Brand E",
"merit", "Easy to use, large capacity, fast speed"));
bulkRequest.add(new IndexRequest("search_vector_test").id("14103")
.source(XContentType.JSON,
"text_field", "Brand B 64GB ultra-high-speed mobile storage card UHS-1 standard read/write speed up to 30 MB",
"tag", new String[] {"Storage device", "Storage card", "SD card"},
"brand", "Brand B",
"merit", "Large capacity, fast speed, easy to use"));
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
Pure vector search
SearchRequest searchRequest = new SearchRequest();
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
Map<String, Object> queryBody = Map.of(
"knn", Map.of(
"text_field_embedding", Map.of(
"query_text", "Storage card",
"k", 10
)
)
);
searchSourceBuilder.size(10);
searchSourceBuilder.query(QueryBuilders.wrapperQuery(new Gson().toJson(queryBody)));
Map<String, String> ext = Map.of("ef_search", "200");
searchSourceBuilder.ext(Collections.singletonList(new LVectorExtBuilder("lvector", ext)));
searchRequest.source(searchSourceBuilder);
searchRequest.indices("search_vector_test");
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(searchResponse);Response
search responseBody = {
"took": 46,
"timed_out": false,
"terminated_early": false,
"num_reduce_phases": 0,
"_shards": {
"total": 2,
"successful": 2,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 7,
"relation": "eq"
},
"max_score": 0.7433592,
"hits": [
{
"_index": "search_vector_test",
"_id": "8195",
"_score": 0.7433592,
"_source": {
"text_field": "Brand E Class4 32G TF card (micro SD) mobile phone storage card",
"merit": "Large capacity, fast speed, easy to use, good quality",
"tag": [
"Storage device",
"Storage card",
"SD card"
],
"brand": "Brand E"
}
},
{
"_index": "search_vector_test",
"_id": "14103",
"_score": 0.7116537,
"_source": {
"text_field": "Brand B 64GB ultra-high-speed mobile storage card UHS-1 standard read/write speed up to 30 MB",
"merit": "Large capacity, fast speed, easy to use",
"tag": [
"Storage device",
"Storage card",
"SD card"
],
"brand": "Brand B"
}
},
{
"_index": "search_vector_test",
"_id": "13316",
"_score": 0.6831677,
"_source": {
"text_field": "Brand E 101 G2 32GB USB flash drive",
"merit": "Easy to use, large capacity, fast speed",
"tag": [
"Storage device",
"USB drive",
"USB flash drive"
],
"brand": "Brand E"
}
},
{
"_index": "search_vector_test",
"_id": "3982",
"_score": 0.64234203,
"_source": {
"text_field": "Brand A stylish energy-saving wireless mouse (grass green) (Glare. Rhythm. Stylish dancing mouse 12-month battery life High-precision optical tracking engine Ultra-fine receiver with 10-meter transmission distance)",
"merit": "Easy to use, attractive appearance",
"tag": [
"Mouse",
"Electronic products"
],
"brand": "Brand A"
}
},
{
"_index": "search_vector_test",
"_id": "6797",
"_score": 0.6357207,
"_source": {
"text_field": "Brand D two-head rechargeable electric shaver",
"merit": "Easy to use, attractive appearance",
"tag": [
"Home appliances",
"Electric shaver"
],
"brand": "Brand D"
}
},
{
"_index": "search_vector_test",
"_id": "323519",
"_score": 0.62445086,
"_source": {
"text_field": "Brand B optical mouse (classic black) (Smart auto-pairing/1000 DPI high-precision optical engine)",
"merit": "Good quality, fast delivery, attractive appearance, easy to use",
"tag": [
"Mouse",
"Electronic products"
],
"brand": "Brand B"
}
},
{
"_index": "search_vector_test",
"_id": "300265",
"_score": 0.62144196,
"_source": {
"text_field": "Brand C in-ear headphones white (classic and stylish)",
"merit": "Attractive appearance, good quality",
"tag": [
"Headphones",
"Electronic products"
],
"brand": "Brand C"
}
}
]
}
}Vector search with property filtering
SearchRequest searchRequest = new SearchRequest();
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
Map<String, Object> queryBody = Map.of(
"knn", Map.of(
"text_field_embedding", Map.of(
"query_text", "Storage card",
"k", 10,
"filter", Map.of(
"bool", Map.of(
"filter", List.of(
Map.of("match", Map.of("merit", "Good quality")),
Map.of("term", Map.of("brand", "Brand E")),
Map.of("terms", Map.of("tag", List.of("SD card", "Storage card")))
)
)
)
)
)
);
searchSourceBuilder.size(10);
searchSourceBuilder.query(QueryBuilders.wrapperQuery(new Gson().toJson(queryBody)));
Map<String, String> ext = Map.of("filter_type", "efficient_filter", "ef_search", "200");
searchSourceBuilder.ext(Collections.singletonList(new LVectorExtBuilder("lvector", ext)));
searchRequest.source(searchSourceBuilder);
searchRequest.indices("search_vector_test");
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(searchResponse);Response
search responseBody = {
"took": 73,
"timed_out": false,
"_shards": {
"total": 2,
"successful": 2,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 0.7433592,
"hits": [
{
"_index": "search_vector_test",
"_id": "8195",
"_score": 0.7433592,
"_source": {
"text_field": "Brand E Class4 32G TF card (micro SD) mobile phone storage card",
"merit": "Large capacity, fast speed, easy to use, good quality",
"tag": [
"Storage device",
"Storage card",
"SD card"
],
"brand": "Brand E"
}
}
]
}
}Vector search with full-text and property filtering
SearchRequest searchRequest = new SearchRequest();
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
Map<String, Object> queryBody = Map.of(
"knn", Map.of(
"text_field_embedding", Map.of(
"query_text", "Storage card",
"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", "Storage card")))
)
)
),
Map.of(
"bool", Map.of(
"filter", List.of(
Map.of("match", Map.of("merit", "Good quality")),
Map.of("term", Map.of("brand", "Brand E")),
Map.of("terms", Map.of("tag", List.of("SD card", "Storage card")))
)
)
)
)
)
),
"k", 10
)
)
);
searchSourceBuilder.size(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", "1",
"ef_search", "200");
searchSourceBuilder.ext(Collections.singletonList(new LVectorExtBuilder("lvector", ext)));
searchRequest.source(searchSourceBuilder);
searchRequest.indices("search_vector_test");
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(searchResponse);Result
search responseBody = {
"took": 95,
"timed_out": false,
"terminated_early": false,
"num_reduce_phases": 0,
"_shards": {
"total": 2,
"successful": 2,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 1.0,
"hits": [
{
"_index": "search_vector_test",
"_id": "8195",
"_score": 1.0,
"_source": {
"text_field": "Brand E Class4 32G TF card (micro SD) mobile phone storage card",
"merit": "Large capacity, fast speed, easy to use, good quality",
"tag": [
"Storage device",
"Storage card",
"SD card"
],
"brand": "Brand E"
}
}
]
}
}