Write and query automatic embeddings

Updated at:

The automatic embedding feature uses built-in pre-trained models to automatically convert text into vectors. This eliminates the complex process of manually defining vector fields required by traditional methods. This topic describes how to use the Java Low Level REST Client to write and query data with the automatic embedding feature in Lindorm Vector Engine.

Prerequisites

  • The installed Java environment must be JDK 1.8 or a later version.

  • 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.

    Important

    If 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 using advanced features, you need to install the Java Low Level REST Client and connect to the search engine. For more information, see Preparations.

Overview of the procedure

Step

Engine involved

Description

Deploy an embedding model in the AI engine

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.

Create a write pipeline

Search engine

Create a write pipeline in the search engine. This pipeline automatically converts text data into vector data (embedding) when you write data.

Create a write pipeline

Search engine

Create a query pipeline in the search engine. This pipeline automatically converts text data into vector data when you query data.

Create an index and specify pipelines

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.

Write data

Vector engine, Search engine

Use the specified write pipeline to automatically convert the written text data into vector data.

Query 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.

Important

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 pipeline for a search engine

Create two types of pipelines in the search engine to automatically process vectors during data writes and queries.

Create a write pipeline

String jsonString = """
  {
    "description": "demo_chunking pipeline",
    "processors": [
      {
        "text-embedding": {
          "inputFields": ["text_field"],
          "outputFields": ["text_field_embedding"],
          "userName": "user", // The username for the AI engine
          "password": "test****", // The password for 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 = "write_embedding_pipeline";
Request createPipelineRequest = new Request("PUT", "/_ingest/pipeline/" + pipelineName);
createPipelineRequest.setJsonEntity(jsonString);
Response response = restClient.performRequest(createPipelineRequest);
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println("createPipeline responseBody = " + responseBody);

Parameters

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 you want to convert into a vector.

outputFields

The vector field that stores the result of the 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 bge_m3_model.

Note

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 for the AI engine
          "password": "test****", // The password for 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 = restClient.performRequest(createPipelineRequest);
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println("create knnSearch Pipeline responseBody = " + responseBody);

Parameters

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 you want to convert into a vector. This acts as a placeholder.

outputFields

The vector field that stores the result of the 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 bge_m3_model.

Note

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 one, you must specify the required pipelines.

Create a vector index

// Create an index
String indexName = "search_vector_test";
Request indexRequest = new Request("PUT", "/" + indexName);
String jsonString = """
{
 "settings" : {
    "index": {
      "number_of_shards": 2,
      "knn": true,
      "default_pipeline": "write_embedding_pipeline",
      "search.default_pipeline": "knnsearch_pipeline"
    }
  },
  "mappings": {
    "_source": {
      "excludes": ["text_field_embedding"]
    },
    "properties": {
      "text_field": {
        "type": "text",
        "analyzer": "ik_max_word" 
      },
      "text_field_embedding": {
        "type": "knn_vector",
        "dimension": 1024,
        "method": {
          "engine": "lvector",
          "name": "hnsw", 
          "space_type": "cosinesimil",
          "parameters": {
            "m": 24,
            "ef_construction": 500
         }
       }
      },
      "tag": {
          "type": "keyword"
      },
      "brand": {
          "type": "keyword"
      },
      "merit" : {
        "type": "text",
        "analyzer": "ik_max_word"  
      }
    }
  }
}
""";
indexRequest.setJsonEntity(jsonString);
Response response = restClient.performRequest(indexRequest);
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println("createIndex responseBody = " + responseBody);

Modify the settings of an existing vector index

If you have an existing vector index, you can modify its configuration to specify the pipelines for data writes and queries to meet your business requirements.

String pipelineName = "write_embedding_pipeline";
String knnPipelineName = "knnsearch_pipeline";
String indexName = "vector_test6";
Request linkPipelineRequest = new Request("PUT", "/" + indexName + "/_settings");
String jsonString = """
  {
    "index": {
      "default_pipeline": "%s",
      "search.default_pipeline": "%s"
    }
  }
""".formatted(pipelineName, knnPipelineName);
linkPipelineRequest.setJsonEntity(jsonString);
Response response = restClient.performRequest(linkPipelineRequest);
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println("linkPipeline responseBody = " + responseBody);
}

Write data

Because a write pipeline is specified, when you write data, the text in the text_field is written to the index. The pipeline also encodes the text from the text_field into a vector and writes the vector to the text_field_embedding field.

Request bulkRequest = new Request("POST", "/_bulk");
String jsonString = """
{ "index" : { "_index" : "search_vector_test", "_id" : "3982" } }
{ "text_field" : "Brand A stylish energy-saving wireless mouse (grass green) (dazzling, dynamic, stylish dancing mouse, 12-month battery life, high-precision optical tracking engine, ultra-fine receiver with 10-meter transmission range)", "tag": ["mouse", "electronic product"], "brand":"Brand A", "merit":"easy to use, good design"}
{ "index" : { "_index" : "search_vector_test", "_id" : "323519" } }
{ "text_field" : "Brand B optical mouse (classic black) (intelligent auto-pairing/1000 DPI high-precision optical engine)", "tag": ["mouse", "electronic product"], "brand":"Brand B", "merit":"good quality, fast delivery, good design, easy to use"}
{ "index" : { "_index" : "search_vector_test", "_id" : "300265" } }
{ "text_field" : "Brand C in-ear headphones, white (classic and stylish)", "tag": ["headphones", "electronic product"], "brand":"Brand C", "merit":"good design, good quality"}
{ "index" : { "_index" : "search_vector_test", "_id" : "6797" } }
{ "text_field" : "Brand D two-head rechargeable electric shaver", "tag": ["home appliance", "electric shaver"], "brand":"Brand D", "merit":"easy to use, good design"}
{ "index" : { "_index" : "search_vector_test", "_id" : "8195" } }
{ "text_field" : "Brand E Class4 32G TF card (micro SD) mobile phone memory card", "tag": ["storage device", "memory card", "SD card"], "brand":"Brand E", "merit":"large capacity, fast speed, easy to use, good quality"}
{ "index" : { "_index" : "search_vector_test", "_id" : "13316" } }
{ "text_field" : "Brand E 101 G2 32GB USB drive", "tag": ["storage device","USB drive", "flash drive"], "brand":"Brand E", "merit":"easy to use, large capacity, fast speed"}
{ "index" : { "_index" : "search_vector_test", "_id" : "14103" } }
{ "text_field" : "Brand B 64GB supreme high-speed mobile memory card, UHS-1 standard, read/write speed up to 30MB", "tag": ["storage device", "memory card", "SD card"], "brand":"Brand B", "merit":"large capacity, fast speed, easy to use"}
""";
bulkRequest.setJsonEntity(jsonString);
Response response = restClient.performRequest(bulkRequest);
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println("bulkWriteDoc responseBody = " + responseBody);

Query data

Pure vector search

Request searchRequest = new Request("POST", "/" + indexName + "/_search?pretty");
String jsonString = """
{
  "size": 10,
  "_source": true,
  "query": {
    "knn": {
      "text_field_embedding": {
        "query_text": "memory card",
        "k": 10
      }
    }
  },
  "ext": {
    "lvector": {
      "ef_search": "200"
    }
  }
}  
""";
searchRequest.setJsonEntity(jsonString);
Response response = restClient.performRequest(searchRequest);
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println("search responseBody = " + responseBody);

Results

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 memory card",
          "merit": "large capacity, fast speed, easy to use, good quality",
          "tag": [
            "storage device",
            "memory card",
            "SD card"
          ],
          "brand": "Brand E"
        }
      },
      {
        "_index": "search_vector_test",
        "_id": "14103",
        "_score": 0.7116537,
        "_source": {
          "text_field": "Brand B 64GB supreme high-speed mobile memory card, UHS-1 standard, read/write speed up to 30MB",
          "merit": "large capacity, fast speed, easy to use",
          "tag": [
            "storage device",
            "memory card",
            "SD card"
          ],
          "brand": "Brand B"
        }
      },
      {
        "_index": "search_vector_test",
        "_id": "13316",
        "_score": 0.6831677,
        "_source": {
          "text_field": "Brand E 101 G2 32GB USB drive",
          "merit": "easy to use, large capacity, fast speed",
          "tag": [
            "storage device",
            "USB drive",
            "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) (dazzling, dynamic, stylish dancing mouse, 12-month battery life, high-precision optical tracking engine, ultra-fine receiver with 10-meter transmission range)",
          "merit": "easy to use, good design",
          "tag": [
            "mouse",
            "electronic product"
          ],
          "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, good design",
          "tag": [
            "home appliance",
            "electric shaver"
          ],
          "brand": "Brand D"
        }
      },
      {
        "_index": "search_vector_test",
        "_id": "323519",
        "_score": 0.62445086,
        "_source": {
          "text_field": "Brand B optical mouse (classic black) (intelligent auto-pairing/1000 DPI high-precision optical engine)",
          "merit": "good quality, fast delivery, good design, easy to use",
          "tag": [
            "mouse",
            "electronic product"
          ],
          "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": "good design, good quality",
          "tag": [
            "headphones",
            "electronic product"
          ],
          "brand": "Brand C"
        }
      }
    ]
  }
}

Vector and Property Filtering

Request searchRequest = new Request("POST", "/" + indexName + "/_search?pretty");
String jsonString = """
{
  "size": 10,
  "_source": true,
  "query": {
    "knn": {
      "text_field_embedding": {
        "query_text": "memory card",
        "k": 10,
        "filter": {
          "bool": {
            "filter": [{
              "match": {
                "merit": "good quality"
              }
            },
            {
              "term": {
                "brand": "Brand E"
              }
            },
            {
              "terms": {
                "tag": ["SD card", "memory card"]
              }
            }]
          }
        }
      }
    }
  },
  "ext": {
    "lvector": {
      "filter_type": "efficient_filter",
      "ef_search": "200"
    }
  }
}
""";
searchRequest.setJsonEntity(jsonString);
Response response = restClient.performRequest(searchRequest);
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println("search responseBody = " + responseBody);

Results

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 memory card",
          "merit": "large capacity, fast speed, easy to use, good quality",
          "tag": [
            "storage device",
            "memory card",
            "SD card"
          ],
          "brand": "Brand E"
        }
      }
    ]
  }
}

Vector + Full-Text + Attribute Filtering

Request searchRequest = new Request("POST", "/" + indexName + "/_search?pretty");
String jsonString = """
{
  "size": 10,
  "_source": true,
  "query": {
    "knn": {
      "text_field_embedding": {
        "query_text": "memory card",
        "filter": {
          "bool": {
            "must": [{
              "bool": {
                "must": [{
                  "match": {
                    "text_field": {
                      "query": "memory card"
                    }
                  }
                }]
              }
            },
            {
              "bool": {
                "filter": [{
                  "match": {
                    "merit": "good quality"
                  }
                },
                {
                  "term": {
                    "brand": "Brand E"
                  }
                },
                {
                  "terms": {
                    "tag": ["SD card", "memory card"]
                  }
                }]
              }
            }]
          }
        },
        "k": 10
      }
    }
  },
  "ext": {
    "lvector": {
      "filter_type": "efficient_filter",
      "hybrid_search_type": "filter_rrf",
      "rrf_rank_constant": "1",
      "ef_search": "200"
    }
  }
}  
""";
searchRequest.setJsonEntity(jsonString);
Response response = restClient.performRequest(searchRequest);
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println("search responseBody = " + responseBody);

Results

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 memory card",
          "merit": "large capacity, fast speed, easy to use, good quality",
          "tag": [
            "storage device",
            "memory card",
            "SD card"
          ],
          "brand": "Brand E"
        }
      }
    ]
  }
}