使用PV_GRAPH向量索引
向量字段支持的PV_GRAPH算法属于深度优化的HNSW算法,可支持向量标量联合过滤特性。使用联合标量过滤特性时,相较于后置过滤和布尔查询,可大幅提升结果的填充率和查询性能。
前提条件
已经参考向量检索的集群规划完成集群创建,集群必须是7.10.2版本Elasticsearch集群。
创建索引
- 登录云搜索服务管理控制台。
- 在“集群管理”页面,选择需要启用向量检索的集群,单击操作列“Kibana”,登录Kibana界面。
- 单击左侧导航栏的“Dev Tools”,执行如下命令创建向量索引。
创建一个名为“my_index”的索引,该索引包含一个名为“my_vector”的向量字段和两个子标签字段“country”和“category”。
PUT my_index { "settings": { "index": { "vector": true } }, "mappings": { "properties": { "my_vector": { "type": "vector", "dimension": 2, "indexing": true, "algorithm": "PV_GRAPH", "metric": "euclidean", "sub_fields": ["country", "category"] } } } }
创建索引参数说明请见表1。
PV_GRAPH索引算法“metric”参数仅支持取值为“euclidean”和“inner_product”。
导入向量和标量数据
针对使用了PV_GRPAH索引算法和“sub_fields”的字段,支持如下数据写入语法,其中联合标量字段仅支持写入keyword类型数据,且支持多值、单值场景。
# 写入单条数据 POST my_index/_doc { "my_vector": { "data": [1.0, 1.0], "country": "cn", "category": ["1", "2"] } } # 批量写入多条数据 POST my_index/_bulk {"index": {}} {"my_vector": {"data": [1.0, 2.0], "country": "cn", "category": "1"}} {"index": {}} {"my_vector": {"data": [2.0, 2.0], "country": "cn", "category": ["1", "2"]}} {"index": {}} {"my_vector": {"data": [2.0, 3.0], "country": "eu", "category": "2"}}
查询向量
基于现有的Elasticsearch接口,在vector下新增filter参数支持向量标量联合过滤特性。标签过滤使用的过滤字段,当前支持json格式 ,支持should、must、must_not、term、terms查询, 语法与Elasticsearch查询语法一致。具体的限制如下。
当前过滤嵌套深度最大为4层 , 其中 :
- must_not不支持嵌套和被嵌套。
- 第一级必须只有一个查询关键词(must等),不支持多个关键词并列。
涉及指定联合过滤的标量字段,即创建索引时sub_fields所定义的字段,仅在向量索引类型为PV_GRAPH类型生效。当指定的过滤字段不存在时,过滤请求失效,当作无过滤条件处理。
# 单标签单值匹配查询示例 GET my_index/_search { "query": { "vector": { "my_vector": { "vector": [1.0, 1.0], "topk": 10, "filter": { "term": { "country": "cn" } } } } } } # 单标签多值匹配查询示例 GET my_index/_search { "query": { "vector": { "my_vector": { "vector": [1.0, 1.0], "topk": 10, "filter": { "terms": { "country": ["cn", "eu"] } } } } } } # 多标签匹配查询示例 GET my_index/_search { "query": { "vector": { "my_vector": { "vector": [1.0, 1.0], "topk": 10, "filter": { "must": [ { "term": {"country": "cn"} }, { "terms": {"category": ["1", "2"]} } ] } } } } } # must_not匹配查询示例 GET my_index/_search { "query": { "vector": { "my_vector": { "vector": [1.0, 1.0], "topk": 10, "filter": { "must_not": [ { "term": {"country": "eu"} } ] } } } } }
向量查询参数说明请见表1。