Fork me on GitHub

向量数据库

 

 

 

 

 


 

 

Elasticsearch 从 2022 年 2 月发布的 8.0 版本开始,提供了基于向量的搜索和自然语言处理(NLP)功能。

 

下图清楚地展示了向量搜索引擎的工作原理。它涉及以下几个步骤:

 

  • 将原始实体(如歌曲、图像或文本)转换为数字表示(向量 Embedding);

  • 使用距离度量来表示向量之间的相似性;

  • 使用近似最近邻算法(ANN)搜索与查询相关的数据。

 

 

向量搜索图

 

与 Apache Solr 类似,Elasticsearch 在内部也使用 Apache Lucene 作为其搜索引擎,因此许多底层概念、数据结构和算法同样适用于两者。

 

在这种情况下,基于向量的搜索是构建在 Apache Lucene HNSW(Hierarchical Navigable Small World graph)上的,也就是 Lucene 9 中的原生 ANN(近似最近邻)。

 

实施基于 Elasticsearch 的神经搜索的端到端流程如下:

 

  • 下载 Elasticsearch

  • 外部生成向量

  • 为向量搜索创建 Elasticsearch 索引

  • 索引文档

  • 利用向量字段进行搜索

 

Elastic 8.0 允许用户在 Elasticsearch 中使用自定义或第三方的基于 PyTorch 开发的语言模型进行推断,但需要 Platinum 或 Enterprise 订阅才能体验到完整的机器学习功能。

 

以下是自动从语料库创建向量 Embedding 的 Python 脚本:

 

https://github.com/SeaseLtd/vector-search-elastic-tutorial/blob/main/from_text_to_vectors/batch-sentence-transformers.py

 

案例 1 文档:

 

The presence of communication amid scientific minds was equally important to the success of the Manhattan Project as scientific intellect was. The only cloud hanging over the impressive achievement of the atomic researchers and engineers is what their success truly meant; hundreds of thousands of innocent lives obliterated.

 

它将输出一个包含相应向量的文件:

 

sys.argv[2] = “/path/to/vector_documents_10k.tsv”

 

案例 1 文档:

 

  •  
0.0367823,0.072423555,0.04770486,0.034890372,0.061810732,0.002282318,0.05258357,0.013747136,...,0.0054274425

 

 

接下来通过localhost的API创建索引
curl http://localhost:9200/neural_index/ -XPUT -H 'Content-Type: application/json' -d '{
"mappings": {
    "properties": {
        "general_text_vector": {
            "type": "dense_vector",
            "dims": 384,
            "index": true,
            "similarity": "cosine"
        },
        "general_text": {
            "type": "text"
        },
        "color": {
            "type": "text"
        }
    }
}}'

  

自动创建_bulk API 请求体的方法:

 

https://github.com/SeaseLtd/vector-search-elastic-tutorial/blob/main/indexing_phase/create_body_for_bulk.py

 

由于向量 Embedding 非常长,我们建议使用另一种方法来索引多个文档,即使用 Elasticsearch 的官方 Python 客户端 elasticsearch。

 

以下是我们用于一次性索引文档批次的自定义 Python 脚本:

 

https://github.com/SeaseLtd/vector-search-elastic-tutorial/blob/main/indexing_phase/indexer_elastic.py

 

总结

 

 

我们希望这个教程能帮助你了解如何在 Elasticsearch 中使用基于向量的搜索。

 

还有一些工作可以做,比如支持多值字段,改进重新排序以及与 BERT 和 Transformer 的整合。实际上,这是一个开放的 GitHub 问题 [4],他们正在进行 ANN 搜索的各种改进(包括新功能、增强功能、性能改进等)。

 

如果对你于密集向量的 Elasticsearch 基准测试感兴趣,你可以在这里 [5] 找到一些已发布的结果。

 

>>>>   

参考资料

【1】https://sease.io/wp-admin/post.php?post=56082&action=edit

【2】https://github.com/SeaseLtd/vector-search-elastic-tutorial

【3】https://msmarco.blob.core.windows.net/msmarcoranking/queries.tar.gz

【4】https://github.com/elastic/elasticsearch/issues/84324

【5】https://elasticsearch-benchmarks.elastic.co/#tracks/dense_vector/nightly/default/30d

 

posted @ 2023-07-11 16:36  stardsd  阅读(319)  评论(0编辑  收藏  举报