Write and query automatically vectorized data
The Lindorm vector engine uses embedding models to automatically vectorize text during write and query operations. This eliminates the complex process of manually defining vector fields, which is a requirement of traditional methods. This topic describes how to use Python code to write and query automatically vectorized data in the Lindorm vector engine.
Prerequisites
Python 3.6 or later is installed.
LindormTable is enabled.
You have activated the AI engine.
The search engine is enabled, and its version is 3.9.10 or later. To view or upgrade the version, see Search engine version guide and Minor version update.
ImportantIf your search engine version is earlier than 3.9.10 but the console shows that it is the latest version, contact Lindorm technical support (DingTalk ID: s0s3eg3).
The ECS instance and the Lindorm instance are in the same virtual private cloud (VPC).
The client IP address is added to the Lindorm whitelist.
Preparation
Before creating and using a vector index, you need to connect to the search engine through opensearch-py. The connection method is as follows:
from opensearchpy import OpenSearch, Object
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logging.getLogger('opensearch').setLevel(logging.WARN)
def get_client() -> OpenSearch:
search_client = OpenSearch(
hosts=[{"host": "ld-t4n5668xk31ui****.lindorm.aliyuncs.com", "port": 30070}],
http_auth=("<username>", "<password>"),
http_compress=False,
use_ssl=False,
pool_maxsize=128,
timeout=30
)
return search_clientWhere host, username, and password represent the connection address, default username, and default password of the search engine respectively. For how to obtain them, please refer to View connection information.
Procedure overview
Procedure | Engines involved | Description |
AI engine | Call the AI engine RESTful API to deploy the BGE-M3 embedding model. This model transforms text into vectors. | |
Search engine | Define the data write and query flows in the search engine. Call the BGE-M3 model in the AI engine to transform the write and query text into vectors. | |
| Create or modify a vector index in the vector engine. Attach the write Pipeline and query Pipeline to the index. | |
Step 4: Write data |
| Execute the data write Pipeline. Input the source text data to trigger the BGE-M3 model to generate embeddings. Batch write the text and the corresponding vectors. |
Step 5: Query data |
| Execute the query Pipeline. Input the query text to generate a query vector. Match the text in the vector engine and return the results. |
Step 1: Deploy the embedding model in the AI engine
This topic uses the BGE-M3 model as an example. For more information about the parameters, see Model management. For a list of supported models, see Model list.
url = "http://ld-t4n5668xk31ui****-proxy-ai-vpc.lindorm.aliyuncs.com:9002/v1/ai/models/create" # The private network endpoint of the AI engine.
self.headers = {
"Content-Type": "application/json; charset=utf-8",
"x-ld-ak": "<username>", # The username for the AI engine.
"x-ld-sk": "<password>" # The password for the AI engine.
}
data = {
"model_name": "bge_m3_model",
"model_path": "huggingface://BAAI/bge-m3",
"task": "FEATURE_EXTRACTION",
"algorithm": "BGE_M3",
"settings": {"instance_count": "2"}
}
response = requests.post(url, data=json.dumps(data), headers=self.headers)
json_response = response.json()
if response.status_code != 200 or json_response["success"] is False:
print("http request failed, status code: {}".format(json_response["msg"])) Step 2: Create a pipeline in the search engine
Create a write pipeline and a query pipeline in the search engine. These pipelines automatically call the embedding model deployed in the DPI engine to manage the entire process, from text parsing to vector representation.
Create a write pipeline
pipeline = {
"description": "demo_chunking pipeline",
"processors": [
{
"text-embedding": {
"inputFields": ["text_field"],
"outputFields": ["text_field_embedding"],
"userName": "root", # Username for the DPI engine
"password": "test****", # Password for the DPI engine
"url": "http://ld-t4n5668xk31ui****-proxy-ai-vpc.lindorm.aliyuncs.com:9002", # VPC endpoint of the DPI engine
"modelName": "bge_m3_model"
}
}
]
}
try:
response = self.client.ingest.put_pipeline(id=self.write_embedding_pipeline, body=pipeline)
print("Create pipeline success", response)
except Exception as e:
print("Create pipeline error ", e) Parameter description
Parameter | Description | Required |
processors | The processor that handles the configuration of write requests. | Yes |
text-embedding | A fixed key that identifies the current pipeline as one for automatic text embedding during writes. | Yes |
inputFields | The text field in the search index that requires vectorization. This field must be the same as the | Yes |
outputFields | The vector field used to store vector data. This field must be the same as the | Yes |
userName | The default username for the Lindorm AI engine. | Yes |
password | Lindorm default password for the AI engine. | Yes |
url | The AI engine endpoint must be the VPC endpoint. | Yes |
modeName | The model name. This topic uses | Yes |
Create a query pipeline
pipeline = {
"request_processors": [
{
"text-embedding": {
"tag": "auto-query-embedding",
"description": "Auto query embedding",
"model_config": {
"inputFields": ["text_field"],
"outputFields": ["text_field_embedding"],
"userName": "root", # Username for the DPI engine
"password": "test****", # Password for the DPI engine
"url": "http://ld-t4n5668xk31ui****-proxy-ai-vpc.lindorm.aliyuncs.com:9002", # VPC endpoint of the DPI engine
"modelName": "bge_m3_model"
}
}
}
]
}
try:
response = self.client.search_pipeline.put(id=self.knn_embedding_pipeline, body=pipeline)
print("Create pipeline success", response)
except Exception as e:
print("Create pipeline error ", e)Parameter description
Parameter | Description | Required |
request_processors | The text processor that handles the configuration of query requests. | Yes |
text-embedding | A fixed key that identifies the current pipeline as one for automatic text embedding during queries. | Yes |
tag | The processor identifier. You can specify a custom value, but it must be unique. | No |
description | The description of the processor. | No |
model_config | A dictionary that contains the specific parameters of the model. | Yes |
inputFields | This parameter must be the same as the inputFields parameter in the write pipeline. This field must be the same as the | Yes |
outputFields | The vector field that corresponds to the text field in inputFields. This field must be the same as the | Yes |
userName | Lindorm AI engine's default username. | Yes |
password | Lindorm AI engine's default password. | Yes |
url | Endpoint of the AI engine. This must be the VPC endpoint. | Yes |
modeName | The model name. This topic uses | Yes |
Step 3: Create a vector index and specify the pipeline
When you create a vector index or modify the settings of an existing one, you must specify the required pipeline. For more information about the parameters, see Create a vector index.
Create a vector index
The text_field and text_field_embedding specified when you create the vector index must match the inputFields and outputFields specified in the write and query pipelines.
index_body = {
"settings": {
"index": {
"number_of_shards": 2,
"knn": True,
"default_pipeline": self.write_embedding_pipeline,
"search.default_pipeline": self.knn_embedding_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"
}
}
}
}
try:
response = self.client.indices.create(index=self.index, body=index_body)
print("Create index success", response)
except Exception as e:
print("Create index error ", e)Modify the settings of an existing vector index
If you have already created a vector index, you can modify its configuration to specify the write and query pipelines.
body = {
"index": {
"default_pipeline": self.write_embedding_pipeline,
"search.default_pipeline": self.knn_embedding_pipeline
}
}
print(self.client.indices.put_settings(index=self.index, body=body))Step 4: Write data
When you write data, the system first writes the original text to the text_field field. Then, based on the write pipeline configured for the vector index, the system automatically calls the BGE-M3 model in the DPI engine. The model encodes the text in the text_field field into a vector and writes the resulting vector data to the text_field_embedding field.
bulk_data = [
{
"index": {"_index": "search_vector_pipeline_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", "electronics"],
"brand": "Brand A",
"merit": "easy to use, beautiful design"
},
{
"index": {"_index": "search_vector_pipeline_test", "_id": "323519"},
"text_field": "Brand B optical mouse (classic black)(intelligent automatic pairing/1000 DPI high-precision optical engine)",
"tag": ["mouse", "electronics"],
"brand": "Brand B",
"merit": "good quality, fast delivery, beautiful design, easy to use"
},
{
"index": {"_index": "search_vector_pipeline_test", "_id": "300265"},
"text_field": "Brand C in-ear headphones white (classic and stylish)",
"tag": ["headphone", "electronics"],
"brand": "Brand C",
"merit": "beautiful design, good quality"
},
{
"index": {"_index": "search_vector_pipeline_test", "_id": "6797"},
"text_field": "Brand D two-head rechargeable electric shaver",
"tag": ["home appliance", "electric shaver"],
"brand": "Brand D",
"merit": "easy to use, beautiful design"
},
{
"index": {"_index": "search_vector_pipeline_test", "_id": "8195"},
"text_field": "Brand E Class4 32G TF card (micro SD) mobile phone storage card",
"tag": ["storage device", "storage card", "SD card"],
"brand": "Brand E",
"merit": "large capacity, fast speed, easy to use, good quality"
},
{
"index": {"_index": "search_vector_pipeline_test", "_id": "13316"},
"text_field": "Brand E 101 G2 32GB USB drive",
"tag": ["storage device", "USB drive", "USB drive"],
"brand": "Brand E",
"merit": "easy to use, large capacity, fast speed"
},
{
"index": {"_index": "search_vector_pipeline_test", "_id": "14103"},
"text_field": "Brand B 64GB ultra-high-speed mobile storage card, UHS-1 standard, read/write speed up to 30 MB",
"tag": ["storage device", "storage card", "SD card"],
"brand": "Brand B",
"merit": "large capacity, fast speed, easy to use"
}
]
response = self.client.bulk(bulk_data, refresh=True)
print(response)Step 5: Query data
The following three query methods are supported:
Pure vector retrieval: Returns results that match the query vector based on vector similarity calculations.
Vector retrieval with attribute filtering: Combines vector similarity retrieval with conditional filtering based on metadata, such as time, category, and label, to retrieve results that match specific attributes.
Vector retrieval with full-text search and attribute filtering: Integrates vector similarity, full-text matching, and attribute condition filtering to perform precise retrieval based on multi-dimensional constraints.
Pure vector retrieval
query = {
"size": 10,
"_source": True,
"query": {
"knn": {
"text_field_embedding": {
"query_text": "storage card",
"k": 10
}
}
},
"ext": {"lvector": {"ef_search": "200"}}
}
response = self.client.search(index=index_name, body=query)
print(response)Response
{
"took": 64,
"timed_out": false,
"terminated_early": false,
"num_reduce_phases": 0,
"_shards": {
"total": 2,
"successful": 2,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 3,
"relation": "eq"
},
"max_score": 0.6915956,
"hits": [
{
"_index": "search_vector_pipeline_test",
"_id": "8195",
"_score": 0.6915956,
"_source": {
"index": {
"_index": "search_vector_pipeline_test",
"_id": "13316"
},
"text_field": "Brand E 101 G2 32GB USB drive",
"merit": "easy to use, large capacity, fast speed",
"tag": ["storage device", "USB drive", "USB drive"],
"brand": "Brand E"
}
},
{
"_index": "search_vector_pipeline_test",
"_id": "300265",
"_score": 0.6262013,
"_source": {
"index": {
"_index": "search_vector_pipeline_test",
"_id": "6797"
},
"text_field": "Brand D two-head rechargeable electric shaver",
"merit": "easy to use, beautiful design",
"tag": ["home appliance", "electric shaver"],
"brand": "Brand D"
}
},
{
"_index": "search_vector_pipeline_test",
"_id": "3982",
"_score": 0.624792,
"_source": {
"index": {
"_index": "search_vector_pipeline_test",
"_id": "323519"
},
"text_field": "Brand B optical mouse (classic black)(intelligent automatic pairing/1000 DPI high-precision optical engine)",
"merit": "good quality, fast delivery, beautiful design, easy to use",
"tag": ["mouse", "electronics"],
"brand": "Brand B"
}
}
]
}
}Vector retrieval with attribute filtering
query = {
"size": 10,
"_source": True,
"query": {
"knn": {
"text_field_embedding": {
"query_text": "storage card",
"k": 10,
"filter": {
"bool": {
"filter": [{
"match": {
"merit": "good quality"
}
},
{
"term": {
"brand": "Brand E"
}
},
{
"terms": {
"tag": ["SD card", "storage card"]
}
}]
}
}
}
}
},
"ext": {
"lvector": {
"filter_type": "efficient_filter",
"hybrid_search_type": "filter_rrf",
"rrf_rank_constant": "1",
"ef_search": "200"
}
}
}
response = self.client.search(index=index_name, body=query)
print(response)Response
{
"took": 3,
"timed_out": false,
"_shards": {
"total": 2,
"successful": 2,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 0,
"relation": "eq"
},
"max_score": null,
"hits": []
}
}Vector retrieval with full-text search and attribute filtering
query = {
"size": 10,
"_source": True,
"query": {
"knn": {
"text_field_embedding": {
"query_text": "storage card",
"filter": {
"bool": {
"must": [{
"bool": {
"must": [{
"match": {
"text_field": {
"query": "storage card"
}
}
}]
}
},
{
"bool": {
"filter": [{
"match": {
"merit": "good quality"
}
},
{
"term": {
"brand": "Brand E"
}
},
{
"terms": {
"tag": ["SD card", "storage card"]
}
}]
}
}]
}
},
"k": 10
}
}
},
"ext": {
"lvector": {
"filter_type": "efficient_filter",
"hybrid_search_type": "filter_rrf",
"rrf_rank_constant": "1",
"ef_search": "200"
}
}
}
response = self.client.search(index=self.index, body=query)
print(response)Response
{
"took": 5,
"timed_out": false,
"terminated_early": false,
"num_reduce_phases": 0,
"_shards": {
"total": 2,
"successful": 2,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 0,
"relation": "eq"
},
"max_score": 0.0,
"hits": []
}
}Complete code example
LindormSearch.py
This module is a basic utility class for interacting with the Lindorm search engine. Its core features include connecting to the search engine, performing index operations, and implementing query logic.
import json
import random
from opensearchpy import OpenSearch
from ldconfig import Config
class LindormSearch:
def __init__(self):
self.random = random.Random(0)
self.top_k = 5
try:
self.client = OpenSearch(
hosts=[{"host": Config.SEARCH_HOST, "port": Config.SEARCH_PORT}],
http_auth=(Config.LD_USER, Config.LD_PASSWORD),
http_compress=False,
use_ssl=False,
)
except Exception as e:
print("Connection search error", e)
def get_index(self, index_name):
print(index_name, self.client.indices.get(index_name))
def bulk_insert(self, index_name, count=1000):
operations = []
for i in range(0, count):
id = self.random.randint(-2 ** 63, 2 ** 63 - 1)
operations.append(json.dumps({"index": {"_index": index_name, "_id": id}}))
operations.append("\n")
vector1 = []
for j in range(0, 3):
vector1.append(self.random.random())
operations.append(json.dumps({"field1": self.random.random(), "vector1": vector1}))
operations.append("\n")
response = self.client.bulk("".join(operations), refresh=True)
print(response)
def knn_search(self, index_name):
query = {
"size": 10,
"query": {
"knn": {
"vector1": {
"vector": [2.3, 3.3, 4.4],
"k": 10
}
}
},
"ext": {"lvector": {"min_score": "0.001"}}
}
response = self.client.search(index=index_name, body=query)
print(response)
def knn_search_with_filter(self, index_name):
query = {
"size": 10,
"query": {
"knn": {
"vector1": {
"vector": [2.3, 3.3, 4.4],
"filter": {
"range": {
"field1": {
"gte": 0
}
}
},
"k": 10
}
}
},
"ext": {"lvector": {"filter_type": "efficient_filter", "ef_search": "100", "k_expand_scope": "2000"}}
}
response = self.client.search(index=index_name, body=query)
print(response)
def text_search(self, text_query, k=int(Config.SEARCH_TOP_K)):
query_body = {
"size": k,
"_source": ["document_id", "chunking_position", "text"],
"query": {
"match": {
self.parent.text_field: text_query
}
}
}
res = self.client.search(index=self.index_name, body=query_body)
return res['hits']['hits']
def vector_search(self, text_query, k=int(Config.SEARCH_TOP_K)):
vector = self.parent.lindormAI.text_embedding(text_query)
query_body = {
"size": k,
"_source": ["document_id", "chunking_position", "text"],
"query": {
"knn": {
self.parent.vector_field: {
"vector": vector,
"k": k
}
}
},
"ext": {"lvector": {"ef_search": "200"}}
}
res = self.client.search(index=self.index_name, body=query_body)
return res['hits']['hits']
def rrf_search(self, text_query, k=int(Config.SEARCH_TOP_K)):
vector = self.parent.lindormAI.text_embedding(text_query)
query_body = {
"size": k,
"_source": ["document_id", "chunking_position", "text"],
"query": {
"knn": {
self.parent.vector_field: {
"vector": vector,
"filter": {
"match": {
self.parent.text_field: text_query,
}
},
"k": k
}
}
},
"ext": {"lvector": {
"hybrid_search_type": "filter_rrf",
"rrf_rank_constant": "60",
"ef_search": "200"
}}
}
res = self.client.search(index=self.index_name, body=query_body)
return res['hits']['hits'] ldconfig.py
Configuration file that stores global parameters, including connection information.
class Config:
# Set global variables. Replace the placeholder values with your actual information.
LD_ES_HOST = "ld-t4n5668xk31ui****-proxy-search-vpc.lindorm.aliyuncs.com" # Endpoint of the search engine
LD_ES_PORT = 30070 # Port of the search engine
LD_USER = "root" # Default username for the search and DPI engines
LD_PASSWORD = "test****" # Default initial password for the search and DPI engines
# DPI engine connection information. Replace the placeholder values.
AI_HOST = "http://ld-t4n5668xk31ui****-proxy-ai-vpc.lindorm.aliyuncs.com" # Endpoint of the DPI engine
AI_PORT = 9002 # Port of the DPI engine
SEARCH_TOP_K = 10 # Set an appropriate value as needed. HnswIndexWithPipeline.py
This module implements the complete automatic vectorization process and encapsulates all operations from Step 1 to Step 5.
import json
import requests
from LindormSearch import LindormSearch
from ldconfig import Config
class HnswIndexWithPipeline(LindormSearch):
def __init__(self):
super().__init__()
self.index = "search_vector_pipeline_test"
self.write_embedding_pipeline = "write_embedding_pipeline"
self.knn_embedding_pipeline = "knn_embedding_pipeline"
def create_ai_model(self):
url = "http://{}:{}/v1/ai/models/create".format(Config.AI_HOST, int(Config.AI_PORT))
headers = {
"Content-Type": "application/json; charset=utf-8",
"x-ld-ak": Config.LD_USER,
"x-ld-sk": Config.LD_PASSWORD
}
data = {
"model_name": "bge_m3_model",
"model_path": "huggingface://BAAI/bge-m3",
"task": "FEATURE_EXTRACTION",
"algorithm": "BGE_M3",
"settings": {"instance_count": "2"}
}
response = requests.post(url, data=json.dumps(data), headers=headers)
json_response = response.json()
if response.status_code != 200 or json_response["success"] is False:
print("http request failed, status code: {}".format(json_response["msg"]))
def check_pipeline_exists(self) -> bool:
try:
print(self.client.ingest.get_pipeline(id=self.write_embedding_pipeline))
return True
except Exception as e:
return False
def create_write_embedding_pipeline(self):
if self.check_pipeline_exists():
print("Pipeline {} exists".format(self.write_embedding_pipeline))
return
inner_ai_host = Config.AI_HOST
if "-pub" in inner_ai_host:
inner_ai_host = inner_ai_host.replace("-pub", "-vpc")
pipeline = {
"description": "demo_chunking pipeline",
"processors": [
{
"text-embedding": {
"inputFields": ["text_field"],
"outputFields": ["text_field_embedding"],
"userName": Config.LD_USER,
"password": Config.LD_PASSWORD,
"url": "http://{}:{}".format(inner_ai_host, int(Config.AI_PORT)),
"modeName": "bge_m3_model"
}
}
]
}
try:
response = self.client.ingest.put_pipeline(id=self.write_embedding_pipeline, body=pipeline)
print("Create pipeline success", response)
except Exception as e:
print("Create pipeline errr ", e)
def check_knn_pipeline_exists(self) -> bool:
try:
response = self.client.search_pipeline.get(id=self.knn_embedding_pipeline)
print(response)
return True
except Exception as e:
return False
def create_knnsearch_pipeline(self):
if self.check_knn_pipeline_exists():
print("Pipeline {} exists".format(self.knn_embedding_pipeline))
# If the pipeline already exists, the current policy is to skip it. To adjust parameters and recreate the pipeline, comment out the return statement below.
return
inner_ai_host = Config.AI_HOST
if "-pub" in inner_ai_host:
inner_ai_host = inner_ai_host.replace("-pub", "-vpc")
pipeline = {
"request_processors": [
{
"text-embedding": {
"tag": "auto-query-embedding",
"description": "Auto query embedding",
"model_config": {
"inputFields": ["text_field"],
"outputFields": ["text_field_embedding"],
"userName": Config.LD_USER,
"password": Config.LD_PASSWORD,
"url": "http://{}:{}".format(inner_ai_host, int(Config.AI_PORT)),
"modeName": "bge_m3_model"
}
}
}
]
}
try:
response = self.client.search_pipeline.put(id=self.knn_embedding_pipeline, body=pipeline)
print("Create pipeline success", response)
except Exception as e:
print("Create pipeline errr ", e)
def create_index_with_pipeline(self):
index_body = {
"settings": {
"index": {
"number_of_shards": 2,
"knn": True,
"default_pipeline": self.write_embedding_pipeline,
"search.default_pipeline": self.knn_embedding_pipeline
}
},
"mappings": {
"_source": {
"excludes": ["text_field_embedding"]
},
"properties": {
"text_field": {
"type": "text",
"analyzer": "ik_max_word"
},
"text_field_embedding": {
"type": "knn_vector",
"dimension": 1024,
"data_type": "float",
"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"
}
}
}
}
try:
response = self.client.indices.create(index=self.index, body=index_body)
print("Create index success", response)
except Exception as e:
print("Create index errr ", e)
def update_index_setting(self):
body = {
"index": {
"default_pipeline": self.write_embedding_pipeline,
"search.default_pipeline": self.knn_embedding_pipeline
}
}
print(self.client.indices.put_settings(index=self.index, body=body))
def bulk_insert_docs(self):
bulk_data = [
{
"index": {"_index": "search_vector_pipeline_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", "electronics"],
"brand": "Brand A",
"merit": "easy to use, beautiful design"
},
{
"index": {"_index": "search_vector_pipeline_test", "_id": "323519"},
"text_field": "Brand B 1090 optical mouse (classic black)(intelligent automatic pairing/1000 DPI high-precision optical engine)",
"tag": ["mouse", "electronics"],
"brand": "Brand B",
"merit": "good quality, fast delivery, beautiful design, easy to use"
},
{
"index": {"_index": "search_vector_pipeline_test", "_id": "300265"},
"text_field": "Brand C in-ear headphones white (classic and stylish)",
"tag": ["headphone", "electronics"],
"brand": "Brand C",
"merit": "beautiful design, good quality"
},
{
"index": {"_index": "search_vector_pipeline_test", "_id": "6797"},
"text_field": "Brand D two-head rechargeable electric shaver",
"tag": ["home appliance", "electric shaver"],
"brand": "Brand D",
"merit": "easy to use, beautiful design"
},
{
"index": {"_index": "search_vector_pipeline_test", "_id": "8195"},
"text_field": "Brand E Class4 32G TF card (micro SD) mobile phone storage card",
"tag": ["storage device", "storage card", "SD card"],
"brand": "Brand E",
"merit": "large capacity, fast speed, easy to use, good quality"
},
{
"index": {"_index": "search_vector_pipeline_test", "_id": "13316"},
"text_field": "Brand E 101 G2 32GB USB drive",
"tag": ["storage device", "USB drive", "USB drive"],
"brand": "Brand E",
"merit": "easy to use, large capacity, fast speed"
},
{
"index": {"_index": "search_vector_pipeline_test", "_id": "14103"},
"text_field": "Brand B 64GB ultra-high-speed mobile storage card, UHS-1 standard, read/write speed up to 30 MB",
"tag": ["storage device", "storage card", "SD card"],
"brand": "Brand B",
"merit": "large capacity, fast speed, easy to use"
}
]
response = self.client.bulk(bulk_data, refresh=True)
print(response)
def knn_search(self, index_name):
query = {
"size": 10,
"_source": True,
"query": {
"knn": {
"text_field_embedding": {
"query_text": "storage card",
"k": 10
}
}
},
"ext": {"lvector": {"ef_search": "200"}}
}
response = self.client.search(index=index_name, body=query)
print(response)
def knn_search_with_filter(self, index_name):
query = {
"size": 10,
"_source": True,
"query": {
"knn": {
"text_field_embedding": {
"query_text": "storage card",
"k": 10,
"filter": {
"bool": {
"filter": [{
"match": {
"merit": "good quality"
}
},
{
"term": {
"brand": "Brand E"
}
},
{
"terms": {
"tag": ["SD card", "storage card"]
}
}]
}
}
}
}
},
"ext": {
"lvector": {
"filter_type": "efficient_filter",
"ef_search": "200"
}
}
}
response = self.client.search(index=index_name, body=query)
print(response)
def rrf_search_with_filter(self):
query = {
"size": 10,
"_source": True,
"query": {
"knn": {
"text_field_embedding": {
"query_text": "storage card",
"filter": {
"bool": {
"must": [{
"bool": {
"must": [{
"match": {
"text_field": {
"query": "storage card"
}
}
}]
}
},
{
"bool": {
"filter": [{
"match": {
"merit": "good quality"
}
},
{
"term": {
"brand": "Brand E"
}
},
{
"terms": {
"tag": ["SD card", "storage card"]
}
}]
}
}]
}
},
"k": 10
}
}
},
"ext": {
"lvector": {
"filter_type": "efficient_filter",
"hybrid_search_type": "filter_rrf",
"rrf_rank_constant": "1",
"ef_search": "200"
}
}
}
response = self.client.search(index=self.index, body=query)
print(response)
if __name__ == '__main__':
hnsw = HnswIndexWithPipeline()
hnsw.create_ai_model()
hnsw.create_write_embedding_pipeline()
hnsw.create_knnsearch_pipeline()
hnsw.create_index_with_pipeline()
hnsw.update_index_setting()
hnsw.get_index(hnsw.index)
hnsw.bulk_insert_docs()
hnsw.knn_search(hnsw.index)
hnsw.knn_search_with_filter(hnsw.index)
hnsw.rrf_search_with_filter()