Elasticsearch:使用 Elasticsearch 向量搜索和 FastAPI 构建文本搜索应用程序

这篇具有很好参考价值的文章主要介绍了Elasticsearch:使用 Elasticsearch 向量搜索和 FastAPI 构建文本搜索应用程序。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Elasticsearch:使用 Elasticsearch 向量搜索和 FastAPI 构建文本搜索应用程序,Elasticsearch,Elastic,AI,elasticsearch,fastapi,大数据,搜索引擎,nlp,全文检索

在我的文章 “Elastic:开发者上手指南” 的 “NLP - 自然语言处理及矢量搜索”,我对 Elastic Stack 所提供的矢量搜索有大量的描述。其中很多的方法需要使用到 huggingface.co 及 Elastic 的机器学习。这个对于许多的开发者来说,意味着付费使用。在那些方案里,带有机器学习的 inference processor 是收费的。还有那个上传的 eland 也是收费的。

在今天的文章中,我们来介绍另外一种方法来进行矢量搜素。我们绕过使用 eland 来进行上传模型。取而代之的是使用 Python 应用来上传我们已经生成好的 dense_vector 字段值。 我们将首先使用数据摄取脚本将数据摄取到 Elasticsearch 中。 该脚本将使用本地托管的 Elasticsearch 和 SentenceTransformer 库连接到 Elasticsearch 并执行文本嵌入。

在下面的展示中,我使用最新的 Elastic Stack 8.8.1 来进行展示,尽管它适用于其他版本的 Elastic Stack 8.x 版本。

ingest.py

from elasticsearch import Elasticsearch
from sentence_transformers import SentenceTransformer

USERNAME = "elastic"
PASSWORD = "z5nxTriCD4fi7jSS=GFM"
ELATICSEARCH_ENDPOINT = "https://localhost:9200"
CERT_FINGERPRINT = "783663875df7ae1daf3541ab293d8cd48c068b3dbc2d9dd6fa8a668289986ac2"

# Connect to Elasticsearch
es = Elasticsearch(ELATICSEARCH_ENDPOINT, 
                   ssl_assert_fingerprint = (CERT_FINGERPRINT),
                   basic_auth=(USERNAME, PASSWORD),
                   verify_certs = False)
resp = es.info()
print(resp)

# Index name
index_name = "test1"

# Example data
data = [
    {"id": 1, "text": "The sun slowly set behind the mountains, casting a golden glow across the landscape. The air was crisp and cool, a gentle breeze rustling through the leaves of the trees. Birds chirped in the distance, their melodic songs filling the air. As I walked along the winding path, I couldn't help but marvel at the beauty of nature surrounding me. The scent of wildflowers wafted through the air, intoxicating and refreshing. It was a moment of tranquility, a moment to escape from the chaos of everyday life and immerse myself in the serenity of the natural world."},
    {"id": 2, "text": "The bustling city streets were filled with the sound of car horns and chatter. People hurried past, their faces lost in a sea of anonymity. Skyscrapers towered above, their reflective glass windows shimmering in the sunlight. The aroma of street food filled the air, mingling with the scent of exhaust fumes. Neon signs flashed with vibrant colors, advertising the latest products and services. It was a city that never slept, a constant whirlwind of activity and excitement. Amidst the chaos, I navigated through the crowds, searching for moments of connection and inspiration."},
    {"id": 3, "text": "The waves crashed against the shore, each one a powerful force of nature. The sand beneath my feet shifted with every step, as if it was alive. Seagulls soared overhead, their calls echoing through the salty air. The ocean stretched out before me, its vastness both awe-inspiring and humbling. I closed my eyes and listened to the symphony of the sea, the rhythm of the waves lulling me into a state of tranquility. It was a place of solace, a place where the worries of the world melted away and all that remained was the beauty of the natural world."},
    {"id": 4, "text": "The old bookstore was a treasure trove of knowledge and stories. Rows upon rows of bookshelves lined the walls, each one filled with books of every genre and era. The scent of aged paper and ink filled the air, creating an atmosphere of nostalgia and adventure. As I perused the shelves, my fingers lightly grazing the spines of the books, I felt a sense of wonder and curiosity. Each book held the potential to transport me to another world, to introduce me to new ideas and perspectives. It was a sanctuary for the avid reader, a place where imagination flourished and stories came to life."}
]

# Create Elasticsearch index and mapping
if not es.indices.exists(index=index_name):
    es_index = {
        "mappings": {
            "properties": {
                "text": {"type": "text"},
                "embedding": {"type": "dense_vector", "dims": 768}
            }
        }
    }
    es.indices.create(index=index_name, body=es_index, ignore=[400])

# Upload documents to Elasticsearch with text embeddings
model = SentenceTransformer('quora-distilbert-multilingual')

for doc in data:
    # Calculate text embeddings using the SentenceTransformer model
    embedding = model.encode(doc["text"], show_progress_bar=False)

    # Create document with text and embedding
    document = {
        "text": doc["text"],
        "embedding": embedding.tolist()
    }

    # Index the document in Elasticsearch
    es.index(index=index_name, id=doc["id"], document=document)

为了运行上面的应用,我们需要安装 elasticsearch 及 sentence_transformers 包:

pip install sentence_transformers elasticsearch

如果我们对上面的 Python 连接到 Elasticsearch 还比较不清楚的话,请详细阅读我之前的文章 “Elasticsearch:关于在 Python 中使用 Elasticsearch 你需要知道的一切 - 8.x”。

我们首先在数据摄取脚本中导入必要的库,包括 Elasticsearch 和 SentenceTransformer。 我们使用 Elasticsearch URL 建立与 Elasticsearch 的连接。 我们定义 index_name 变量来保存 Elasticsearch 索引的名称。

接下来,我们将示例数据定义为字典列表,其中每个字典代表一个具有 ID 和文本的文档。 这些文档模拟了我们想要搜索的数据。 你可以根据您的特定数据源和元数据提取要求自定义脚本。

我们检查 Elasticsearch 索引是否存在,如果不存在,则使用适当的映射创建它。 该映射定义了我们文档的字段类型,包括作为文本的文本字段和作为维度为 768 的密集向量的嵌入(embedding)字段。

我们使用 quora-distilbert-multilingual 预训练文本嵌入模型来初始化 SentenceTransformer 模型。 该模型可以将文本编码为长度为 768 的密集向量。

对于示例数据中的每个文档,我们使用 model.encode() 函数计算文本嵌入并将其存储在嵌入变量中。 我们使用文本和嵌入字段创建一个文档字典。 最后,我们使用 es.index() 函数在 Elasticsearch 中索引文档。

现在我们已经将数据提取到 Elasticsearch 中,让我们继续使用 FastAPI 创建搜索 API。

main.py

from fastapi import FastAPI
from elasticsearch import Elasticsearch
from sentence_transformers import SentenceTransformer

USERNAME = "elastic"
PASSWORD = "z5nxTriCD4fi7jSS=GFM"
ELATICSEARCH_ENDPOINT = "https://localhost:9200"
CERT_FINGERPRINT = "783663875df7ae1daf3541ab293d8cd48c068b3dbc2d9dd6fa8a668289986ac2"

# Connect to Elasticsearch
es = Elasticsearch(ELATICSEARCH_ENDPOINT, 
                   ssl_assert_fingerprint = (CERT_FINGERPRINT),
                   basic_auth=(USERNAME, PASSWORD),
                   verify_certs = False)

app = FastAPI()

@app.get("/search/")
async def search(query: str):
    print("query string is: ", query)
    model = SentenceTransformer('quora-distilbert-multilingual')
    embedding = model.encode(query, show_progress_bar=False)

    # Build the Elasticsearch script query
    script_query = {
        "script_score": {
            "query": {"match_all": {}},
            "script": {
                "source": "cosineSimilarity(params.query_vector, 'embedding') + 1.0",
                "params": {"query_vector": embedding.tolist()}
            }
        }
    }

    # Execute the search query
    search_results = es.search(index="test1", body={"query": script_query})

    # Process and return the search results
    results = search_results["hits"]["hits"]
    return {"results": results}

@app.get("/")
async def root():
    return {"message": "Hello World"}

要运行 FastAPI 应用程序,请将代码保存在文件中(例如 main.py)并在终端中执行以下命令:

uvicorn main:app --reload
$ pwd
/Users/liuxg/python/fastapi_vector
$ uvicorn main:app --reload
INFO:     Will watch for changes in these directories: ['/Users/liuxg/python/fastapi_vector']
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [95339] using WatchFiles
/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/elasticsearch/_sync/client/__init__.py:395: SecurityWarning: Connecting to 'https://localhost:9200' using TLS with verify_certs=False is insecure
  _transport = transport_class(
INFO:     Started server process [95341]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     127.0.0.1:59811 - "GET / HTTP/1.1" 200 OK

这将启动 FastAPI 开发服务器。 然后,您可以访问 http://localhost:8000/search/ 的搜索端点并提供查询参数来执行搜索。 结果将作为 JSON 响应返回。

确保根据你的要求自定义代码,例如添加错误处理、身份验证和修改响应结构。我们做如下的搜索:

Elasticsearch:使用 Elasticsearch 向量搜索和 FastAPI 构建文本搜索应用程序,Elasticsearch,Elastic,AI,elasticsearch,fastapi,大数据,搜索引擎,nlp,全文检索

Elasticsearch:使用 Elasticsearch 向量搜索和 FastAPI 构建文本搜索应用程序,Elasticsearch,Elastic,AI,elasticsearch,fastapi,大数据,搜索引擎,nlp,全文检索

很显然,当我们搜索语句 “The sun slowly set behind the mountains” 的时候,第一个文档是最相近的。其它的文档没有那么相近,但是他们也会作为候选结果返回给用户。文章来源地址https://www.toymoban.com/news/detail-698529.html

到了这里,关于Elasticsearch:使用 Elasticsearch 向量搜索和 FastAPI 构建文本搜索应用程序的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包赞助服务器费用

相关文章

  • 快速入门:使用 Gemini Embeddings 和 Elasticsearch 进行向量搜索

    快速入门:使用 Gemini Embeddings 和 Elasticsearch 进行向量搜索

    Gemini 是 Google DeepMind 开发的多模态大语言模型家族,作为 LaMDA 和 PaLM 2 的后继者。由 Gemini Ultra、Gemini Pro 和 Gemini Nano 组成,于 2023 年 12 月 6 日发布,定位为 OpenAI 的竞争者 GPT-4。 本教程演示如何使用 Gemini API 创建嵌入并将其存储在 Elasticsearch 中。 Elasticsearch 将使我们能够执

    2024年01月21日
    浏览(14)
  • Elasticsearch:在 Elasticsearch 中使用 NLP 和向量搜索增强聊天机器人功能

    Elasticsearch:在 Elasticsearch 中使用 NLP 和向量搜索增强聊天机器人功能

    作者:Priscilla Parodi 会话界面已经存在了一段时间,并且作为协助各种任务(例如客户服务、信息检索和任务自动化)的一种方式而变得越来越流行。 通常通过语音助手或消息应用程序访问,这些界面模拟人类对话,以帮助用户更有效地解决他们的查询。 随着技术的进步,聊

    2024年02月07日
    浏览(17)
  • 使用 ElasticSearch 作为知识库,存储向量及相似性搜索

    使用 ElasticSearch 作为知识库,存储向量及相似性搜索

    在当今大数据时代,快速有效地搜索和分析海量数据成为了许多企业和组织的重要需求。 Elasticsearch 作为一款功能强大的分布式搜索和分析引擎,为我们提供了一种优秀的解决方案。除了传统的文本搜索, Elasticsearch 还引入了向量存储的概念,以实现更精确、更高效的相似性

    2024年02月10日
    浏览(12)
  • 使用 ElasticSearch 作为知识库,存储向量及相似性搜索_elasticsearch cosinesimilarity(1)

    使用 ElasticSearch 作为知识库,存储向量及相似性搜索_elasticsearch cosinesimilarity(1)

    下面基于上篇文章使用到的 Chinese-medical-dialogue-data 中文医疗对话数据作为知识内容进行实验。 本篇实验使用 ES 版本为: 7.14.0 二、Chinese-medical-dialogue-data 数据集 GitHub 地址如下: https://github.com/Toyhom/Chinese-medical-dialogue-data 数据分了 6 个科目类型: 数据格式如下所示: 其中

    2024年04月11日
    浏览(8)
  • Elasticsearch:使用 ELSER 文本扩展进行语义搜索

    Elasticsearch:使用 ELSER 文本扩展进行语义搜索

    在今天的文章里,我来详细地介绍如何使用 ELSER  进行文本扩展驱动的语义搜索。 如果你还没有安装好自己的 Elasticsearch 及 Kibana,请参考如下的链接来进行安装: 如何在 Linux,MacOS 及 Windows 上进行安装 Elasticsearch Kibana:如何在 Linux,MacOS 及 Windows 上安装 Elastic 栈中的 Kiba

    2024年02月07日
    浏览(14)
  • Elasticsearch:使用向量搜索来查询及比较文字 - NLP text embedding

    Elasticsearch:使用向量搜索来查询及比较文字 - NLP text embedding

    Elastic Stack 机器学习功能可以生成嵌入(embeddings),你可以使用它在非结构化文本中搜索或比较不同的文本片段。传统上,我们在搜索文本的时候,更加倾向于把文字进行分词,然后再对 token 进行比对: 在上面,我们在文字中完全或部分匹配分词后的 token,从而完成我们的

    2024年02月09日
    浏览(11)
  • Elasticsearch:使用 huggingface 模型的 NLP 文本搜索

    Elasticsearch:使用 huggingface 模型的 NLP 文本搜索

    本博文使用由 Elastic 博客 title 组成的简单数据集在 Elasticsearch 中实现 NLP 文本搜索。你将为博客文档建立索引,并使用摄取管道生成文本嵌入。 通过使用 NLP 模型,你将使用自然语言在博客文档上查询文档。 如果你还没有安装好自己的 Elasticsearch 及 Kibana,请参考如下的链接

    2024年02月07日
    浏览(9)
  • fastapi结合Manticore Search、elasticsearch、mysql实现全文搜索

    fastapi结合Manticore Search、elasticsearch、mysql实现全文搜索

    创建测试表 测试表插入数据 表字段描述 字段意义 mysql数据同步到es es查看数据(Elasticvue插件)   mysql数据同步到Manticore 注:Manticore 和 Mysql 使用pymysql即mysql客户端 Manticore 数据查询(工具Webyog SQLyog)   es安全认证连接(参考官网) 按fields查询方法封装,输入参数fields 筛选器,

    2024年02月12日
    浏览(8)
  • Elasticsearch:使用在本地计算机上运行的 LLM 以及 Ollama 和 Langchain 构建 RAG 应用程序

    Elasticsearch:使用在本地计算机上运行的 LLM 以及 Ollama 和 Langchain 构建 RAG 应用程序

    无需 GPU 的隐私保护 LLM。在本博客中,我将演示使用不同的工具 Ollama 构建的 RAG 应用程序。 与本文相关的所有源代码均已发布在 github上。 请克隆存储库以跟随文章操作。我们可以通过如下的方式来克隆: Ollama 是一个轻量级且灵活的框架,专为在个人计算机上本地部署 LL

    2024年04月16日
    浏览(15)
  • 使用Elasticsearch构建强大的搜索和分析引擎

    Elasticsearch是一个基于Lucene的分布式搜索和分析引擎,被广泛用于处理大规模的文本数据。无论是构建全文搜索引擎、进行日志分析还是实现实时数据可视化,Elasticsearch都是一个强大而灵活的工具。本文将带您逐步了解如何使用Elasticsearch,并构建您自己的搜索和分析应用。

    2024年02月04日
    浏览(15)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包