当前位置:   article > 正文

elasticsearch 关于向量化检索_elasticsearch 向量化

elasticsearch 向量化

1、elasticsearch使用的是8.5.0

索引和mapping构建:

  1. PUT image-index
  2. {
  3. "mappings": {
  4. "properties": {
  5. "mydatavector": {
  6. "type": "dense_vector",
  7. "dims": 3,
  8. "index": true,
  9. "similarity": "dot_product"
  10. },
  11. "title": {
  12. "type": "text"
  13. }
  14. }
  15. }
  16. }

 2、数据入库:使用python的elasticsearch 包如果为7.11的,可以同时兼容6.x、7.x、8.x版本

from sentence_transformers import SentenceTransformer

from elasticsearch import Elasticsearch

from elasticsearch.helpers import bulk

encoder = SentenceTransformer('你的模型本地路径')

client2 = Elasticsearch(['http://用户名:密码@IP:PORT'])

def batch_write(data):
    actions = [
        {

            "_index": "index_name",  # 替换为您的索引名称
            "_source": d,
            "_id": d["id"]

        }
        for d in data
    ]

    try:
        bulk(client2, actions)

    except Exception as e:
        print("bach write error")

def es_data_mapping(json_data):

    question = json_data["title"].strip().replace(" ", "")

    #注意这里的normalize_embeddings=True和mapping中的"similarity": "dot_product"相对应

    doc_vector = encoder.encode([question],convert_to_tensor=False,normalize_embeddings=True).tolist()[0]

    json_data["mydatavector"] = doc_vector

    return json_data

batch_write_num = 200

def write_data_2_es():

    data_list = [{"id":"1","title":"大家好"}]

    write_list = []

    for each in data_list:

        write_list.append(es_data_mapping(each))

        if len(write_list)>batch_write_num:

            batch_write(write_list)

            write_list.clear()

    if len(write_list) > 0:

        batch_write(write_list)

        write_list.clear()

if __name__ == '__main__':

    write_data_2_es()

3、查询检索:

POST http://IP:PORT/INDEX_NAME/_search

{

"_source": ["mydatavector","title"],

"min_score": 0.5,

    "knn": {
        "field": "mydatavector",

        "query_vector": [0,0,0],
        "k": 3,
        "num_candidates": 100,

        "filter": {
            "bool": {
                "must": [

                    {
                        "terms": {
                            "title": [

                                "狗头"
                            ]
                        }

                    }
                ]
            }

        }
    }
}

}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/1010291
推荐阅读
相关标签
  

闽ICP备14008679号