<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
  <channel>
    <title><![CDATA[Priscilla Parodi - Elasticsearch Labs]]></title>
    <description><![CDATA[Articles and tutorials from the Search team at Elastic]]></description>
    <copyright><![CDATA[© 2026. Elasticsearch B.V. All Rights Reserved]]></copyright>
    <image>
      <title><![CDATA[Priscilla Parodi - Elasticsearch Labs]]></title>
      <url>https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt1121c0bf0e8a6e65/6a88da6340a1841030ef456f/search-labs-thumbnail.png</url>
      <link>https://www.elastic.co/cn/search-labs/author/priscilla-parodi</link>
    </image>
    <link>https://www.elastic.co/cn/search-labs/author/priscilla-parodi</link>
    <atom:link href="https://www.elastic.co/cn/search-labs/rss/author/priscilla-parodi.xml" rel="self" type="application/rss+xml"/>
    <language><![CDATA[cn]]></language>
    <lastBuildDate>Sat, 12 Sep 2026 14:15:49 GMT</lastBuildDate>
  <item>
    <title><![CDATA[人工智能剽窃利用 Elasticsearch 检测剽窃行为]]></title>
    <description><![CDATA[以下是如何使用 Elasticsearch 检查人工智能剽窃，重点是使用 NLP 模型和矢量搜索的用例。]]></description>
    <content:encoded><![CDATA[<p>剽窃可以是<strong>直接剽窃</strong>，即抄袭部分或全部内容；也可以是<strong>转述剽窃</strong>，即对作者的作品进行改写，改动一些词或短语。</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/bltb6e139760e56ec98/6a171147dc55de0ad2e00edf/5d7073187fda829438aeec8d3a1194a5bea2ba57-1440x347.png" alt="" /><p>灵感和意译是有区别的。阅读一篇内容，获得启发，然后用自己的语言来探讨这个想法，即使得出的结论相似，也是有可能的。</p><p>虽然剽窃一直是讨论的话题，但内容的加速生产和发布使其具有现实意义，并构成了持续的挑战。</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/bltc2af1678cb04506b/6a171149cf4f251c2ab2d257/a0b9a98d729db09dae0a79315c001e6763c12704-1400x1016.png" alt="" /><p>这种挑战并不局限于书籍、学术研究或司法文件，在这些领域经常会进行抄袭检查。它还可以延伸到报纸甚至社交媒体。</p><p>随着信息的丰富和出版的便捷，如何在可扩展的层面上有效检查抄袭行为？</p><p>大学、政府机构和公司使用的工具多种多样，虽然直接的<a href="https://www.elastic.co/search-labs/lexical-and-semantic-search-with-elasticsearch">词汇搜索</a>可以有效检测直接抄袭，但主要的挑战在于识别<strong>转述的内容。</strong></p><h2>利用生成式人工智能检测剽窃行为</h2><p>生成式人工智能带来了新的挑战。人工智能生成的内容在复制时是否被视为抄袭？</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt8a1ed1b6fa3f1a56/6a17114b4a531bc40736aa69/9345b28d6d27c37469bc38e823c41780b4eabfe5-1440x875.png" alt="" /><p>例如，<a href="https://openai.com/">OpenAI</a>的<a href="https://openai.com/policies/terms-of-use">使用条款</a>规定，OpenAI 不会对 API 为用户生成的内容主张版权。在这种情况下，使用生成式人工智能的个人可以随意使用生成的内容，而无需引用。</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/bltbc2e08ab5b808e38/6a17114dab7f086cbadb9f93/e1f415f69a247666f02ddc81468944920c874cd7-968x814.png" alt="" /><p>不过，是否接受使用生成式人工智能来提高效率仍是一个讨论话题。</p><p>为了对剽窃检测做出贡献，OpenAI 开发了一个<a href="https://huggingface.co/roberta-base-openai-detector">检测模型</a>，但后来承认其准确性不够高。</p><p><em>"我们认为，这对于独立检测来说精度还不够高，需要与基于元数据的方法、人工判断和公众教育相结合，才能更加有效。"</em></p><p>然而，随着更多工具的出现，现在有了更多检测抄袭的选择，即使是在转述和人工智能内容的情况下。</p><h2>使用 Elasticsearch 检测剽窃行为</h2><p>有鉴于此，在本博客中，我们将利用自然语言处理（NLP）模型和矢量搜索（plagiarism detection）来探索元数据搜索之外的另一个使用案例。</p><p>我们利用<a href="https://www.sbert.net/"> SentenceTransformers</a> 提供的<a href="https://sbert.net/datasets/emnlp2016-2018.json"> 数据集（</a> 其中包含 NLP 相关文章），通过<a href="https://github.com/elastic/elasticsearch-labs/blob/main/supporting-blog-content/plagiarism-detection-with-elasticsearch/plagiarism_detection_es.ipynb"> Python 示例 进行了演示。</a>我们通过 "语义文本相似性 "检查摘要是否抄袭，"语义文本相似性 "考虑的是用之前导入 Elasticsearch 的<a href="https://huggingface.co/sentence-transformers/all-mpnet-base-v2">文本嵌入模型</a>生成的 "摘要 "嵌入。此外，为了识别人工智能生成的内容--人工智能剽窃，还将 OpenAI 开发的<a href="https://huggingface.co/roberta-base-openai-detector">NLP 模型</a>导入 Elasticsearch。</p><p>下图说明了数据流：</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt0464f88d3ed12070/6a17114fab7f084905db9f97/1ad89c98a2f42a497548ca3947749bad54ec1172-1440x880.png" alt="" /><p>在使用<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/inference-processor.html"> 推理处理器</a> <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/ingest.html">的摄取管道</a> 中，"抽象 "段落被映射为一个 768 维的向量，即 "abstract_vector.predicted_value"。</p><p>绘图：</p>"abstract_vector.predicted_value": { # Inference results field
"type": "dense_vector", 
"dims": 768, # model embedding_size
"index": "true", 
"similarity": "dot_product" # When indexing vectors for approximate kNN search, you need to specify the similarity function for comparing the vectors.
<p>矢量表示之间的相似性使用矢量相似性度量来衡量，该度量使用 "相似性 "<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/dense-vector.html#dense-vector-params">参数</a>来定义。</p><p><a href="https://en.wikipedia.org/wiki/Cosine_similarity">余弦</a>是默认的相似度量，计算公式为"(1 + cosine(query, vector))/ 2'.除非您需要保留原始矢量，并且无法事先对它们进行归一化处理，否则执行余弦相似性的最有效方法就是将所有矢量归一化为单位长度。这有助于避免在搜索过程中执行额外的矢量长度计算，而应使用 "dot_product"。</p><p>在同一管道中，另一个包含<a href="https://huggingface.co/roberta-base-openai-detector">文本分类模型</a>的推理处理器会检测内容是可能由人类撰写的 "真实 "内容，还是可能由人工智能撰写的 "虚假 "内容，并将 "openai-detector.predicted_value "添加到每个文档中。</p><p>摄取管道：</p>client.ingest.put_pipeline( 
    id="plagiarism-checker-pipeline",
    processors = [
    {
      "inference": { #for ml models - to infer against the data that is being ingested in the pipeline
        "model_id": "roberta-base-openai-detector", #text classification model id
        "target_field": "openai-detector", # Target field for the inference results
        "field_map": { #Maps the document field names to the known field names of the model.
        "abstract": "text_field" # Field matching our configured trained model input. 
        }
      }
    },
    {
      "inference": {
        "model_id": "sentence-transformers__all-mpnet-base-v2", #text embedding model id
        "target_field": "abstract_vector", # Target field for the inference results
        "field_map": {
        "abstract": "text_field" # Field matching our configured trained model input. Typically for NLP models, the field name is text_field.
        }
      }
    }
    
  ]
)
<p>在查询时，同样的文本嵌入模型也被用于在 "query_vector_builder "对象中生成查询 "model_text "的向量表示。</p><p>k-nearest neighbor (kNN) 搜索会根据相似度量找到与查询向量最近的 k 个向量。</p><p>每份文档的  分数都来自相似度，确保分数越大，排名越靠前。这意味着文件在语义上更加相似。因此，我们打印了三种可能性：如果得分&gt; 0.9，我们认为是 "高度相似"；如果&lt; 0.7，是 "低度相似"，否则是 "中度相似"。您可以根据自己的使用情况，灵活设置不同的阈值，以确定哪种程度的 _score 是否属于抄袭。</p><p>此外，还进行了文本分类，以检查文本查询中是否有人工智能生成的元素。</p><p>查询：</p>from elasticsearch import Elasticsearch
from elasticsearch.client import MlClient

#duplicated text - direct plagiarism test

model_text = 'Understanding and reasoning about cooking recipes is a fruitful research direction towards enabling machines to interpret procedural text. In this work, we introduce RecipeQA, a dataset for multimodal comprehension of cooking recipes. It comprises of approximately 20K instructional recipes with multiple modalities such as titles, descriptions and aligned set of images. With over 36K automatically generated question-answer pairs, we design a set of comprehension and reasoning tasks that require joint understanding of images and text, capturing the temporal flow of events and making sense of procedural knowledge. Our preliminary results indicate that RecipeQA will serve as a challenging test bed and an ideal benchmark for evaluating machine comprehension systems. The data and leaderboard are available at http://hucvl.github.io/recipeqa.'

response = client.search(index='plagiarism-checker', size=1,
    knn={
        "field": "abstract_vector.predicted_value",
        "k": 9,
        "num_candidates": 974,
        "query_vector_builder": { #The 'all-mpnet-base-v2' model is also employed to generate the vector representation of the query in a 'query_vector_builder' object.
            "text_embedding": {
                "model_id": "sentence-transformers__all-mpnet-base-v2",
                "model_text": model_text
            }
        }
    }
)

for hit in response['hits']['hits']:
    score = hit['_score']
    title = hit['_source']['title']
    abstract = hit['_source']['abstract']
    openai = hit['_source']['openai-detector']['predicted_value']
    url = hit['_source']['url']

    if score &gt; 0.9:
        print(f"\nHigh similarity detected! This might be plagiarism.")
        print(f"\nMost similar document: '{title}'\n\nAbstract: {abstract}\n\nurl: {url}\n\nScore:{score}\n\n")

        if openai == 'Fake':
            print("This document may have been created by AI.\n")

    elif score &lt; 0.7:
        print(f"\nLow similarity detected. This might not be plagiarism.")

        if openai == 'Fake':
            print("This document may have been created by AI.\n")

    else:
        print(f"\nModerate similarity detected.")
        print(f"\nMost similar document: '{title}'\n\nAbstract: {abstract}\n\nurl: {url}\n\nScore:{score}\n\n")

        if openai == 'Fake':
            print("This document may have been created by AI.\n")

ml_client = MlClient(client)

model_id = 'roberta-base-openai-detector' #open ai text classification model

document = [
    {
        "text_field": model_text
    }
]

ml_response = ml_client.infer_trained_model(model_id=model_id, docs=document)

predicted_value = ml_response['inference_results'][0]['predicted_value']

if predicted_value == 'Fake':
    print("\nNote: The text query you entered may have been generated by AI.\n")
<p>输出：</p>High similarity detected! This might be plagiarism.

Most similar document: 'RecipeQA: A Challenge Dataset for Multimodal Comprehension of Cooking Recipes'

Abstract: Understanding and reasoning about cooking recipes is a fruitful research direction towards enabling machines to interpret procedural text. In this work, we introduce RecipeQA, a dataset for multimodal comprehension of cooking recipes. It comprises of approximately 20K instructional recipes with multiple modalities such as titles, descriptions and aligned set of images. With over 36K automatically generated question-answer pairs, we design a set of comprehension and reasoning tasks that require joint understanding of images and text, capturing the temporal flow of events and making sense of procedural knowledge. Our preliminary results indicate that RecipeQA will serve as a challenging test bed and an ideal benchmark for evaluating machine comprehension systems. The data and leaderboard are available at[ http://hucvl.github.io/recipeqa](http://hucvl.github.io/recipeqa).

url:[http://aclweb.org/anthology/D18-1166](http://aclweb.org/anthology/D18-1166)

Score:1.0
<p>在本例中，利用数据集中的一个 "摘要 "值作为文本查询 "model_text "后，剽窃行为被识别出来。相似度分数为 1.0，表明相似度很高，即<strong>直接抄袭</strong>。矢量化查询和文档没有被识别为人工智能生成的内容，这在意料之中。</p><p>查询：</p>#similar text - paraphrase plagiarism test 

model_text = 'Comprehending and deducing information from culinary instructions represents a promising avenue for research aimed at empowering artificial intelligence to decipher step-by-step text. In this study, we present CuisineInquiry, a database for the multifaceted understanding of cooking guidelines. It encompasses a substantial number of informative recipes featuring various elements such as headings, explanations, and a matched assortment of visuals. Utilizing an extensive set of automatically crafted question-answer pairings, we formulate a series of tasks focusing on understanding and logic that necessitate a combined interpretation of visuals and written content. This involves capturing the sequential progression of events and extracting meaning from procedural expertise. Our initial findings suggest that CuisineInquiry is poised to function as a demanding experimental platform.'
<p>输出：</p>High similarity detected! This might be plagiarism.

Most similar document: 'RecipeQA: A Challenge Dataset for Multimodal Comprehension of Cooking Recipes'

Abstract: Understanding and reasoning about cooking recipes is a fruitful research direction towards enabling machines to interpret procedural text. In this work, we introduce RecipeQA, a dataset for multimodal comprehension of cooking recipes. It comprises of approximately 20K instructional recipes with multiple modalities such as titles, descriptions and aligned set of images. With over 36K automatically generated question-answer pairs, we design a set of comprehension and reasoning tasks that require joint understanding of images and text, capturing the temporal flow of events and making sense of procedural knowledge. Our preliminary results indicate that RecipeQA will serve as a challenging test bed and an ideal benchmark for evaluating machine comprehension systems. The data and leaderboard are available at[ http://hucvl.github.io/recipeqa](http://hucvl.github.io/recipeqa).

url:[http://aclweb.org/anthology/D18-1166](http://aclweb.org/anthology/D18-1166)

Score:0.9302529

Note: The text query you entered may have been generated by AI.
<p>通过更新文本查询 "model_text"，使用人工智能生成的文本，在传达相同信息的同时尽量减少相似词语的重复，检测到的相似度仍然很高，但得分为 0.9302529，而不是 1.0，这就是<strong>转述剽窃</strong>。人们还预计，由人工智能生成的这一查询会被检测到。</p><p>最后，考虑到文本查询 "model_text "是关于 Elasticsearch 的文本，而不是这些文档的摘要，检测到的相似度为 0.68991005，表明根据所考虑的阈值，相似度较低。</p><p>查询：</p>#different text - not a plagiarism

model_text = 'Elasticsearch provides near real-time search and analytics for all types of data.'
<p>输出：</p>Low similarity detected. This might not be plagiarism.
<p>虽然在人工智能生成的文本查询中，以及在转述和直接复制内容的情况下，都能准确识别出抄袭行为，但在剽窃检测领域中，还需要认识到各个方面的问题。</p><p>在人工智能生成的内容检测方面，我们探索了一种模式，这种模式做出了宝贵的贡献。不过，必须认识到独立检测的固有局限性，因此需要结合其他方法来提高准确性。</p><p>选择文本嵌入模型带来的可变性是另一个考虑因素。使用不同数据集训练的不同模型会产生不同程度的相似性，这突出了所生成的文本嵌入的重要性。</p><p>最后，在这些例子中，我们使用了文件摘要。然而，剽窃检测通常涉及大量文件，因此必须解决文本长度的难题。文本通常会超过模型的标记限制，这就要求在建立嵌入之前将文本分割成块。处理这种情况<a href="https://www.elastic.co/guide/en/elasticsearch/reference/8.11/knn-search.html#nested-knn-search">的实用方法</a>是使用 dense_vector 嵌套结构。</p><h2>结论</h2><p>在这篇博客中，我们讨论了检测抄袭（尤其是在转述和人工智能生成的内容中）所面临的挑战，以及如何利用语义文本相似性和文本分类来实现这一目的。</p><p>结合这些方法，我们提供了一个剽窃检测实例，成功识别了人工智能生成的内容、直接剽窃和转述剽窃。</p><p>我们的主要目标是建立一个过滤系统，简化检测工作，但人工评估对于验证工作仍然至关重要。</p><p>如果您有兴趣了解更多有关语义文本相似性和 NLP 的信息，我们建议您同时查看以下链接：</p><ul><li><p><a href="https://www.elastic.co/what-is/semantic-search">什么是语义搜索？</a></p></li><li><p><a href="https://www.elastic.co/what-is/natural-language-processing">什么是自然语言处理（NLP）？</a></p></li><li><p><a href="https://www.elastic.co/search-labs/blog/lexical-and-semantic-search-with-elasticsearch">使用 Elasticsearch 进行词法和语义搜索</a></p></li><li><p><a href="https://www.elastic.co/search-labs/blog/chunking-via-ingest-pipelines">通过 Ingest 管道对大型文档进行分块，再加上嵌套向量，就能轻松进行通道搜索</a></p></li></ul>]]></content:encoded>
    <link>https://www.elastic.co/search-labs/blog/ai-plagiarism-checker-with-elasticsearch</link>
    <guid isPermaLink="true">https://www.elastic.co/search-labs/blog/ai-plagiarism-checker-with-elasticsearch</guid>
    <category><![CDATA[向量数据库]]></category>
    <category><![CDATA[Python]]></category>
    <dc:creator><![CDATA[Priscilla Parodi]]></dc:creator>
    <enclosure url="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt68a5bc2434a9b03b/6a1711510e2e49a09641a22a/83e05cd4f81799fbb7b7950ed87600e825ec81e9-1024x1024.png" length="0" type="image/png"/>
    <pubDate>Tue, 19 Dec 2023 00:00:00 GMT</pubDate>
  </item>
  <item>
    <title><![CDATA[使用 Elasticsearch 进行词法和语义搜索]]></title>
    <description><![CDATA[在本博客中，我们将探讨使用 Elasticsearch 检索信息的各种方法，重点是词法和语义搜索。]]></description>
    <content:encoded><![CDATA[<p>搜索是根据您的搜索查询或组合查询查找最相关信息的过程，相关搜索结果是与这些查询最匹配的文档。尽管与搜索相关的挑战和方法有多种，但最终目标始终不变，即<strong>尽可能找到问题的最佳答案</strong>。</p><p>考虑到这一目标，在本篇博文中，我们将探讨使用 Elasticsearch 检索信息的不同方法，重点关注文本搜索：<strong>词法搜索和语义搜索。</strong></p><h2>准备工作</h2><p>为此，我们将提供 Python 示例，演示在模拟电子商务产品信息生成的<a href="https://github.com/elastic/elasticsearch-labs/blob/main/supporting-blog-content/lexical-and-semantic-search-with-elasticsearch/products-ecommerce.json">数据集上</a>进行搜索的各种情况。</p><p>该数据集包含 2,500 多种产品，每种产品都有说明。这些产品分为 76 个不同的产品类别，每个类别包含的产品数量各不相同，如下所示：</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt34415151c00ced2b/6a17d8710b0bed6c9bdd342c/4104466050f3024b6bcaf382da2a702650f62227-1440x708.png" alt="" /><p><em>树状地图可视化 - category.keyword 的前 22 个值（产品类别）</em></p><p>安装时您需要</p><ul><li><p>Python 3.6 或更高版本</p></li><li><p><a href="https://www.elastic.co/guide/en/elasticsearch/client/python-api/current/index.html">弹性 Python 客户端</a></p></li><li><p>Elastic 8.8 或更高版本，配备 8GB 内存的机器学习节点</p></li><li><p><a href="https://www.elastic.co/guide/en/machine-learning/8.9/ml-nlp-elser.html">Elastic Learned Sparse EncodeR</a>模型已预装到 Elastic 中，并已在部署中启动</p></li></ul><p>我们将使用 Elastic Cloud，<a href="https://cloud.elastic.co/registration?onboarding_token=vectorsearch&amp;cta=cloud-registration&amp;tech=trial&amp;plcmt=article%20content&amp;pg=search-labs">可免费试用</a>。</p><p>除了本博文提供的搜索查询外，<a href="https://github.com/elastic/elasticsearch-labs/blob/main/supporting-blog-content/lexical-and-semantic-search-with-elasticsearch/ecommerce_dense_sparse_project.ipynb">Python 笔记本</a>还能指导您完成以下过程：</p><ul><li><p>使用 Python 客户端与我们的弹性部署建立连接</p></li><li><p>将文本嵌入模型载入 Elasticsearch 集群</p></li><li><p>创建一个索引，其中包含用于索引特征向量和密集向量的映射。</p></li><li><p>创建带推理处理器的摄取管道，用于文本嵌入和文本扩展</p></li></ul><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt0e95406ece8f08d9/6a17d8731d1b83d32e93e2f4/54a9a490a3b0cf1b9c2228bee8eddd3f566bd435-1418x1102.png" alt="" /><h2>词汇检索--稀疏检索</h2><p>Elasticsearch 根据文本查询对文档进行相关性排序的经典方法是使用<a href="https://en.wikipedia.org/wiki/Okapi_BM25">BM25</a>模型的 Lucene 实现，这是一种<strong>用于词法搜索的稀疏模型</strong>。这种方法沿用了传统的文本搜索方法，即寻找完全匹配的术语。</p><p>为了实现这种搜索，Elasticsearch 通过执行文本分析将文本<strong>字段</strong>数据转换为可搜索格式。</p><p><strong>文本分析</strong> 由<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analyzer-anatomy.html"> 分析器</a> 执行， 分析器 是一套规则，用于管理提取相关词组以供搜索的过程。一个分析器必须有一个<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-tokenizers.html"> 标记符</a>。标记化器接收字符流，并将其分解为单个标记（通常是单个单词），就像下面的例子一样：</p><h3>用于词法搜索的字符串标记化</h3>#Performs text analysis on a string and returns the resulting tokens.

# Define the text to be analyzed
text = "Comfortable furniture for a large balcony"

# Define the analyze request
request_body = {
  "analyzer": "standard",
  "text": text
}

# Perform the analyze request
response = client.indices.analyze(analyzer=request_body["analyzer"], text=request_body["text"])

# Extract and display the analyzed tokens
tokens = [token["token"] for token in response["tokens"]]
print("Analyzed Tokens:", tokens)
<p>输出</p>Analyzed Tokens: ['comfortable', 'furniture', 'for', 'a', 'large', 'balcony']
<p>在本例中，我们使用的是默认分析器--<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-standard-analyzer.html">标准</a>分析器，它能提供基于英语语法的标记化，因此能很好地满足大多数使用要求。标记化可实现单个术语的匹配，但每个标记仍按字面进行匹配。</p><p>如果您想个性化搜索体验，可以选择不同的<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-analyzers.html"> 内置分析器</a>。例如，通过更新代码以使用<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-stop-analyzer.html">停顿分析器</a>，就能在任何非字母字符处将文本分解为词块，并支持删除停顿词。</p>...
# Define the analyze request
request_body = {
  "analyzer": "stop",
  "text": text
}
...
<p>输出</p>Analyzed Tokens: ['comfortable', 'furniture', 'large', 'balcony']
<p>当内置分析器无法满足您的需求时，您可以创建一个<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-custom-analyzer.html"> 自定义分析器</a> ，该 分析器 使用零个或多个<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-charfilters.html"> 字符过滤器</a> 、一个<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-tokenizers.html"> 标记器</a> 和零个或多个<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-tokenfilters.html"> 标记过滤器的</a> 适当组合。</p>"analyzer":  {

  "my_analyzer": {

    "type": "custom", #For custom analyzers, use a type of custom or omit the type parameter.

    "tokenizer": "standard", #Built-in or customized tokenizer

    "filter": ["lowercase", "synonym"] #Built-in or customized token filters
  }
}
<p>在上述结合了标记符号化器和标记符号过滤器的示例中，文本将先由<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-lowercase-tokenfilter.html"> 小写过滤器</a> 进行 小写<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-synonym-tokenfilter.html#:~:text=Elasticsearch%20will%20use%20the%20token,applied%20to%20the%20synonym%20entries."> 处理，然后再由 同义词标记符号过滤器</a> 进行处理。</p><h2>词汇匹配</h2><p><a href="https://www.elastic.co/blog/practical-bm25-part-2-the-bm25-algorithm-and-its-variables">BM25</a>将根据术语的频率及其重要性来衡量文档与给定搜索查询的相关性。</p><p>下面的代码执行<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query.html"> 匹配</a> 查询，搜索最多两个文档，考虑到<em> "ecommerce-search</em><em> "</em> 索引中的 <strong>"描述"</strong><em><strong> 字段值和搜索查询 " 大阳台的舒适家具</strong></em><strong> ".</strong></p><p>改进文档的匹配标准可以提高查询的精确度。然而，更具体的结果是以较低的差异容忍度为代价的。</p># BM25

response = client.search(size=2,
index="ecommerce-search",
query= {
  "match": {
    "description" : {  
      "query": "Comfortable furniture for a large balcony",
      "analyzer": "stop"
    }
  }
}
)

hits = response['hits']['hits']

if not hits:
  print("No matches found")

else:
  for hit in hits:
    score = hit['_score']
    product = hit['_source']['product']
    category = hit['_source']['category']
    description = hit['_source']['description']
    print(f"\nScore: {score}\nProduct: {product}\nCategory: {category}\nDescription: {description}\n")
<p>输出</p>Score: 15.607948
Product: Barbie Dreamhouse
Category: Toys
Description: is a classic Barbie playset with multiple rooms, furniture, a large balcony, a pool, and accessories. It allows kids to create their dream Barbie world.

Score: 9.137739
Product: Comfortable Rocking Chair
Category: Indoor Furniture
Description: enjoy relaxing moments with this comfortable rocking chair. Its smooth motion and cushioned seat make it an ideal piece of furniture for unwinding.
<p>通过分析输出结果，最相关的结果是"<em>芭比娃娃梦幻屋</em>" 产品，属于"<em>玩具</em>" 类别，其描述高度相关，因为其中包括术语"<em>家具</em>" 、"<em>大型"</em>和<em>"阳台</em>" ，这是唯一一个在描述中有 3 个术语符合搜索查询的产品，该产品也是唯一一个在描述中有术语<em>"阳台"</em>的产品。</p><p>排名第二的产品是"<em>舒适摇椅</em>" ，归类为"<em>室内家具</em>" ，其描述包括"<em>舒适</em>" 和"<em>家具</em>" 等术语。数据集中只有 3 种产品至少与该搜索查询的 2 个词匹配，该产品就是其中之一。</p><p><em>"Comfortable"</em>出现在 105 个产品的描述中，<em>"furniture"</em>出现在 4 个产品的描述中，有 4 个不同的类别：<em>玩具</em>、<em>室内家具、室外家具和 "猫狗用品&amp; 玩具"。</em></p><p>正如您所看到的，考虑到该查询，最相关的产品是玩具，第二相关的产品是室内家具。如果你想了解分数计算的详细信息，知道为什么这些文档是匹配的，可以将<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-explain.html"><em>explain</em></a>__query 参数设置为 true。</p><p>尽管这两个结果都是最相关的结果，但考虑到该数据集中的文档数量和术语出现率，查询"<em>大型阳台的舒适家具</em>" 背后的意图是搜索实际大型阳台的家具，不包括玩具和室内家具。</p><p>词法搜索相对<strong>简单快捷</strong>，但也有局限性，因为在不了解用户意图和查询的情况下，不可能总是知道所有可能的术语和同义词。自然语言使用中的一个常见现象是<strong>词汇不匹配</strong>。<a href="https://dl.acm.org/doi/abs/10.1145/32206.32212">研究</a>表明，不同的人（同一领域的专家）对同一事物的命名平均有<strong>80% </strong>不同。</p><p>这些局限性促使我们寻找其他包含语义知识的评分模型。基于变换器的模型擅长处理像自然语言这样的连续输入标记，它通过考虑文档和查询的数学表示来捕捉搜索的基本含义。这样就能对文本进行密集的、上下文感知的矢量表示，为<strong>语义搜索</strong>提供动力，这是一种查找相关内容的精细方法。</p><h2>语义搜索 - 密集检索</h2><p>在这种情况下，将数据转换成有意义的向量值后，利用<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/knn-search.html">k-nearest neighbor（kNN）</a>搜索算法在数据集中找到与查询向量最相似的向量表示。Elasticsearch 支持两种 kNN 搜索方法，即<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/knn-search.html#exact-knn">精确暴力 kNN</a>和<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/knn-search.html#approximate-knn">近似 kNN</a>（也称为 ANN）。</p><p>粗暴的 kNN 可以保证准确的结果，但在处理大型数据集时并不能很好地扩展。近似 kNN 通过牺牲一些精度来提高性能，从而有效地找到近似近邻。</p><p>借助 Lucene 对 kNN 搜索和密集矢量索引的支持，Elasticsearch 利用了分层导航小世界 (HNSW) 算法，该算法在各种<a href="http://ann-benchmarks.com/">ann-benchmark 数据集上</a>都表现出了强大的搜索性能。可以使用下面的示例代码在 Python 中执行近似 kNN 搜索。</p><h3>使用近似 kNN 进行语义搜索</h3># KNN - approximate kNN

response = client.search(index='ecommerce-search', size=2,
knn={
  "field": "description_vector.predicted_value",
  "k": 50, # Number of nearest neighbors to return as top hits.
#The optimal value of k is dependent on the data. It can vary in different scenarios.

  "num_candidates": 500, # Number of nearest neighbor candidates to consider per shard.

#Increasing num_candidates tends to improve the accuracy of the final k results.

  "query_vector_builder": { # Object indicating how to build a query_vector. kNN search enables you to perform semantic search by using a previously deployed text embedding model, the steps for this process are demonstrated in the Python notebook.
    "text_embedding": { 
      "model_id": "sentence-transformers__all-mpnet-base-v2", # Text embedding model id
      "model_text": "Comfortable furniture for a large balcony" # Query
    }
  }
}
)

for hit in response['hits']['hits']:
        
  score = hit['_score']
  product = hit['_source']['product']
  category = hit['_source']['category']
  description = hit['_source']['description']
  print(f"\nScore: {score}\nProduct: {product}\nCategory: {category}\nDescription: {description}\n")
<p>考虑到产品数据集中 " 描述"字段的嵌入情况，该代码块使用 Elasticsearch 的 kNN 返回最多两个描述与"<em>Comfortable furniture for a large balcony</em> " 的矢量化查询 (query_vector_build) 相似的产品。</p><p>产品嵌入之前是在摄取管道中生成的，摄取管道中的推理处理器包含 <em>"</em><a href="https://huggingface.co/sentence-transformers/all-mpnet-base-v2"><em>all-mpnet-base-v2</em></a><em>"</em>文本嵌入模型的推理处理器，根据管道中正在摄取的数据进行推理。</p><p>选择该模型的依据是使用 <em>"</em><a href="https://github.com/UKPLab/sentence-transformers/blob/master/docs/package_reference/sentence_transformer/evaluation.md"><em>句子转换器评估</em></a><em>"</em>在训练过程中，使用不同的类别来评估模型。"all-mpnet-base-v2" 模型在<a href="https://www.sbert.net/docs/pretrained_models.html">Sentence-Transformers</a>排行榜上显示出最佳平均性能，并在<a href="https://huggingface.co/spaces/mteb/leaderboard">大规模文本嵌入基准 (MTEB)</a>排行榜上占据有利位置。该模型预先训练了<a href="https://huggingface.co/microsoft/mpnet-base"> 微软/mpnet-base</a>模型，并在 1B 句子对数据集上进行了微调，将句子映射到 768 维的密集向量空间。</p><p>此外，还有许多其他模型可以使用，特别是那些针对特定领域数据进行微调的模型。</p><p>输出</p>Score: 0.79207325
Product: Patio Sofa Set with Ottoman
Category: Outdoor Furniture
Description: is a versatile and comfortable patio sofa set, including a sofa, ottoman, and coffee table, great for outdoor lounging.

Score: 0.7836937
Product: Patio Sofa Set with Canopy
Category: Outdoor Furniture
Description: is a luxurious and comfortable patio sofa set with a canopy, providing shade and style for outdoor lounging.
<p><em>根据所选模型、</em> <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/knn-search.html#knn-search-filter-example"><em>过滤器</em></a> <em>和</em> <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/knn-search.html#tune-approximate-knn-for-speed-accuracy"><em>近似 kNN 调整</em></a>，输出结果可能会有所不同<em>。</em></p><p>kNN 搜索结果都属于"<em>Outdoor Furniture</em>" 类别，尽管"<em>outdoor</em>" 这个词并没有作为查询的一部分被明确提及，这凸显了语义理解在上下文中的重要性。</p><p>密集矢量搜索有几个优点：</p><ul><li><p>启用语义搜索</p></li><li><p>处理超大数据集的可扩展性</p></li><li><p>灵活处理各种数据类型</p></li></ul><p>不过，<strong>密集矢量搜索也有其自身的挑战</strong>：</p><ul><li><p>为您的使用案例选择合适的嵌入模式</p></li><li><p>选定模型后，可能需要对模型进行微调，以优化特定领域数据集的性能，这一过程需要领域专家的参与</p></li><li><p>此外，索引高维向量的计算成本很高</p></li></ul><h2>语义搜索--学习型稀疏检索</h2><p>让我们来探索另一种方法：学习稀疏检索，这是执行语义搜索的另一种方式。</p><p>作为一种稀疏模型，它利用 Elasticsearch 基于 Lucene 的倒排索引，该索引得益于数十年的优化。不过，这种方法不仅仅是用 BM25 等词汇评分功能添加同义词那么简单。相反，它利用更深层次的语言知识将学习到的联想融入其中，以优化相关性。</p><p>通过扩展搜索查询以包含原始查询中不存在的相关术语，<a href="https://www.elastic.co/guide/en/machine-learning/current/ml-nlp-elser.html">Elastic Learned Sparse Encoder</a>可以<strong>改进稀疏向量嵌入</strong>，如下例所示。</p><h3>利用弹性学习稀疏编码器进行稀疏向量搜索</h3># Elastic Learned Sparse Encoder

response = client.search(index='ecommerce-search', size=2,
query={
  "text_expansion": {
    "ml.tokens": {
      "model_id":"elser_model",
      "model_text":"Comfortable furniture for a large balcony"                
    }
  }
}
)

for hit in response['hits']['hits']:

  score = hit['_score']
  product = hit['_source']['product']
  category = hit['_source']['category']
  description = hit['_source']['description']
  print(f"\nScore: {score}\nProduct: {product}\nCategory: {category}\nDescription: {description}\n")
<p>输出</p>Score: 14.405318
Product: Garden Lounge Set with Side Table
Category: Garden Furniture
Description: is a comfortable and stylish garden lounge set, including a sofa, chairs, and a side table for outdoor relaxation.

Score: 14.281318
Product: Rattan Patio Conversation Set
Category: Outdoor Furniture
Description: is a stylish and comfortable outdoor furniture set, including a sofa, two chairs, and a coffee table, all made of durable rattan material.
<p>本例中的结果包括"<em>Garden Furniture</em>" 类别，该类别提供的产品与"<em>Outdoor Furniture</em>" 非常相似。</p><p>通过分析"ml.tokens" 、"rank_features" 字段，其中包含学习稀疏检索生成的标记，可以明显看出，在生成的各种标记中，有一些术语虽然不是搜索查询的一部分，但其含义仍然相关，如"<em>relax</em>" （舒适）、"<em>sofa</em>" （家具）和"<em>outdoor</em>" （阳台）。</p><p>下面的图片突出显示了查询中的一些术语，包括术语扩展和未扩展术语。</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt7e869985347b19a7/6a17d875e31791dc2c2d56a1/dd86607fce6137d843a3ec002390eaa988b432f9-1440x502.png" alt="" /><p>正如观察到的那样，该模型提供了一种上下文感知搜索，有助于缓解词汇不匹配问题，同时提供更多可解释的结果。在不进行特定领域再训练的情况下，它甚至可以超越密集向量模型。</p><h2>混合搜索：结合词法和语义搜索获得相关结果</h2><p>在搜索方面，没有放之四海而皆准的解决方案。这些检索方法各有所长，但也面临挑战。根据不同的使用情况，最佳选择可能会有所变化。通常情况下，不同检索方法的最佳结果是互补的。因此，为了提高相关性，我们要把每种方法的优势结合起来。</p><p>实现<strong>混合搜索</strong>的方法有多种，包括线性组合、给每个得分加权和互惠等级融合（RRF），其中互惠等级融合无需指定权重。</p><h3>Elasticsearch：词法和语义搜索的两全之策</h3># BM25 + Elastic Learned Sparse Encoder (Linear Combination)

response = client.search(index='ecommerce-search', size=2,

query= {
  "bool": {
    "should": [
    {
      "match": {
        "description" : {  
          "query": "A dining table and comfortable chairs for a large balcony",
          "boost": 1
        }
      }
    },                   
    {
      "text_expansion": {
        "ml.tokens": {
          "model_id": "elser_model",
          "model_text": "A dining table and comfortable chairs for a large balcony",
          "boost": 1
        }
      }
     }
    ]
  }
}
)

# The boost value is 1 for the text expansion and match query. This means that the relevance score of the results of these queries are not boosted. You can specify a boost value to give a weight to each score in the sum. The scores will be calculated as: score = boost value * match_score + boost value * text_expansion_score

for hit in response['hits']['hits']:

  score = hit['_score']
  product = hit['_source']['product']
  category = hit['_source']['category']
  description = hit['_source']['description']
  print(f"\nScore: {score}\nProduct: {product}\nCategory: {category}\nDescription: {description}\n")
<p>在这段代码中，我们使用两个查询值为"<em>大阳台的餐桌和舒适的椅子</em>" 进行了混合搜索。我们没有使用"<em>家具</em>" 作为搜索词，而是指定了我们要查找的内容，并且两个搜索都考虑了相同的字段值，即"描述" 。排名由 BM25 和 ELSER 分数等权重的线性组合确定。</p><p>输出</p>Score: 31.628141
Product: Garden Dining Set with Swivel Rockers
Category: Garden Furniture
Description: is a functional and comfortable garden dining set, including a table and chairs with swivel rockers for easy movement.

Score: 31.334227
Product: Garden Dining Set with Swivel Chairs
Category: Garden Furniture
Description: is a functional and comfortable garden dining set, including a table and chairs with swivel seats for convenience.
<p>在下面的代码中，我们将对查询使用相同的值，但会使用对等排名融合方法合并 BM25（查询参数）和 kNN（knn 参数）的得分，对文档进行合并和排名。</p># BM25 + KNN (RRF)

response = client.search(index='ecommerce-search', size=2,
query={
  "bool": {
    "should": [
    {
      "match": {
        "description": {
        "query": "A dining table and comfortable chairs for a large balcony"
        }
      }
    }
    ]
  }
},
knn={
  "field": "description_vector.predicted_value",
  "k": 50,
  "num_candidates": 500,
  "query_vector_builder": {
    "text_embedding": {
      "model_id": "sentence-transformers__all-mpnet-base-v2",
      "model_text": "A dining table and comfortable chairs for a large balcony"
    }
  }
},
rank={
  "rrf": { # Reciprocal rank fusion
    "window_size": 50, # This value determines the size of the individual result sets per query.
    "rank_constant": 20 # This value determines how much influence documents in individual result sets per query have over the final ranked result set.
  }
}
)

for hit in response['hits']['hits']:
        
  rank = hit['_rank']
  category = hit['_source']['category']
  product = hit['_source']['product']
  description = hit['_source']['description']
  print(f"\nRank: {rank}\nProduct: {product}\nCategory: {category}\nDescription: {description}\n")
<p><em>RRF 功能处于技术预览阶段。在全球大会之前，语法可能会有所改变。</em></p><p>输出</p>Rank: 1
Product: Patio Dining Set with Bench
Category: Outdoor Furniture
Description: is a spacious and functional patio dining set, including a dining table, chairs, and a bench for additional seating.

Rank: 2
Product: Garden Dining Set with Swivel Chairs
Category: Garden Furniture
Description: is a functional and comfortable garden dining set, including a table and chairs with swivel seats for convenience.
<p>在这里，我们还可以使用不同的字段和值，<a href="https://github.com/elastic/elasticsearch-labs/blob/main/supporting-blog-content/lexical-and-semantic-search-with-elasticsearch/ecommerce_dense_sparse_project.ipynb">Python 笔记本</a>中提供了其中一些示例。</p><p>正如您所看到的，有了 Elasticsearch，您就可以两全其美：传统的词法搜索和矢量搜索（无论是稀疏搜索还是密集搜索），以实现您的目标<strong>并找到问题的最佳答案。</strong></p><p>如果您想继续了解这里提到的方法，这些博客会很有用：</p><ul><li><p><a href="https://www.elastic.co/blog/improving-information-retrieval-elastic-stack-hybrid">改进弹性堆栈中的信息检索：混合检索</a></p></li><li><p><a href="https://www.elastic.co/blog/vector-search-elasticsearch-rationale">Elasticsearch 中的矢量搜索：设计背后的原理</a></p></li><li><p><a href="https://www.elastic.co/blog/lexical-ai-powered-search-elastic-vector-database">如何利用 Elastic 的向量数据库获得词法搜索和人工智能驱动搜索的最佳效果</a></p></li><li><p><a href="https://www.elastic.co/blog/may-2023-launch-sparse-encoder-ai-model">介绍 Elastic 学习稀疏编码器：Elastic 用于语义搜索的人工智能模型</a></p></li><li><p><a href="https://www.elastic.co/blog/may-2023-launch-information-retrieval-elasticsearch-ai-model">改进 Elastic Stack 中的信息检索：介绍我们的新检索模型 Elastic Learned Sparse Encoder</a></p></li></ul><p>Elasticsearch 提供了矢量数据库以及构建矢量搜索所需的所有工具：</p><ul><li><p>Elasticsearch<a href="https://www.elastic.co/elasticsearch/vector-database">矢量数据库</a></p></li><li><p>使用 Elastic 的<a href="https://www.elastic.co/enterprise-search/vector-search">矢量搜索</a>用例</p></li></ul><h2>结论</h2><p>在这篇博文中，我们探讨了使用 Elasticsearch 检索信息的各种方法，尤其侧重于文本、词法和语义搜索。为了证明这一点，我们提供了 Python 示例，使用包含电子商务产品信息的数据集展示了不同的搜索场景。</p><p>我们回顾了 BM25 的经典词汇搜索，并讨论了其优势和挑战，如词汇不匹配。我们强调了结合语义知识来克服这一问题的重要性。此外，我们还讨论了实现语义搜索的密集矢量搜索，并介绍了与这种检索方法相关的挑战，包括索引高维矢量时的计算成本。</p><p>另一方面，我们提到稀疏向量的压缩效果特别好。因此，我们讨论了 Elastic 的 "学习稀疏编码器"（Learned Sparse Encoder），该编码器可扩展搜索查询，以包含原始查询中不存在的相关术语。</p><p>在搜索方面，没有放之四海而皆准的解决方案。每种检索方法都有其优势和挑战。因此，我们还讨论了混合搜索的概念。</p><p>正如您所看到的，有了 Elasticsearch，您就可以同时拥有传统词法搜索和矢量搜索这两种搜索方式的优点！</p><p>准备好开始了吗？查看可用的<a href="https://github.com/elastic/elasticsearch-labs/blob/main/supporting-blog-content/lexical-and-semantic-search-with-elasticsearch/ecommerce_dense_sparse_project.ipynb">Python 笔记本</a>并开始<a href="https://cloud.elastic.co/registration?onboarding_token=vectorsearch&amp;cta=cloud-registration&amp;tech=trial&amp;plcmt=article%20content&amp;pg=search-labs">免费试用 Elastic Cloud</a>。</p>]]></content:encoded>
    <link>https://www.elastic.co/search-labs/blog/lexical-and-semantic-search-with-elasticsearch</link>
    <guid isPermaLink="true">https://www.elastic.co/search-labs/blog/lexical-and-semantic-search-with-elasticsearch</guid>
    <category><![CDATA[向量数据库]]></category>
    <category><![CDATA[Python]]></category>
    <category><![CDATA[查询语言]]></category>
    <dc:creator><![CDATA[Priscilla Parodi]]></dc:creator>
    <enclosure url="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/bltbd7e961f594005e7/6a17d80f033c8d981f6bb009/d240bfef29e9d432069059b312dd044eb76eec6c-1440x840.png" length="0" type="image/png"/>
    <pubDate>Tue, 03 Oct 2023 00:00:00 GMT</pubDate>
  </item>
  <item>
    <title><![CDATA[利用 Elasticsearch 中的 NLP 和向量搜索增强聊天机器人功能]]></title>
    <description><![CDATA[探索矢量搜索和 NLP 如何增强聊天机器人的能力，并了解 Elasticsearch 如何促进这一过程。]]></description>
    <content:encoded><![CDATA[<p>对话式界面已经存在了一段时间，作为协助完成各种任务（如客户服务、信息检索和任务自动化）的一种手段，它正变得越来越流行。这些界面通常通过语音助手或消息应用程序访问，模拟人类对话，以帮助用户更高效地解决疑问。</p><p>随着技术的进步，聊天机器人被用来快速处理更复杂的任务，同时还能为用户提供个性化体验。自然语言处理（NLP）使聊天机器人能够处理用户的语言，识别其信息背后的意图，并从中提取相关信息。例如，"命名实体识别 "通过将文本分类，提取文本中的关键信息。情感分析可确定情感基调，而问题解答则可确定查询的 "答案"。NLP 的目标是使算法能够处理人类语言，并完成历史上只有人类才能完成的任务，如在大量文本中查找相关段落、总结文本以及生成新的原创内容。</p><p>这些先进的 NLP 功能建立在一种称为<a href="https://www.elastic.co/what-is/vector-search">向量搜索的</a>技术之上。Elastic 本身支持向量搜索，可执行精确和近似的<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/knn-search.html#knn-search">k-nearest neighbor (kNN) 搜索</a>，还支持 NLP，可直接在 Elasticsearch 中使用自定义或<a href="https://www.elastic.co/guide/en/machine-learning/current/ml-nlp-model-ref.html#ml-nlp-model-ref">第三方模型</a>。</p><p>在这篇博文中，我们将探讨矢量搜索和 NLP 如何增强聊天机器人的能力，并演示 Elasticsearch 如何促进这一过程。首先，让我们简要介绍一下矢量搜索。</p><h2>向量搜索</h2><p>虽然人类可以理解书面语言的含义和上下文，但机器却无法做到这一点。这就是向量的作用所在。通过将文本转换为矢量表示（文本含义的数字表示），机器可以克服这一限制。与传统搜索相比，矢量不依赖于关键词和基于频率的词法搜索，而是使用为数值定义的运算来处理文本数据。</p><p>这样，通过使用"嵌入空间" 中的距离来表示给定查询向量的相似性，向量搜索就能定位具有相似概念或上下文的数据。当数据相似时，相应的向量也会相似。</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt53a615a8ba0ac931/6a17d795fbc5f8b257491910/08542abf8108aace288745b1aca8579b476ddc1b-1440x618.png" alt="" /><p>矢量搜索不仅可用于 NLP 应用，还可用于涉及非结构化数据的其他各种领域，包括图像和视频处理。</p><p>在聊天机器人流程中，用户的查询可能有多种方式，因此，有不同的方法来改进信息检索，以获得更好的用户体验。由于每种方案都有自己的优点和可能的缺点，因此必须考虑到可用的数据和资源，以及训练时间（如适用）和预期的准确性。在下一节中，我们将介绍 NLP 问答模型的这些方面。</p><h2>回答问题</h2><p>问题解答（QA）模型是一种 NLP 模型，旨在回答用自然语言提出的问题。当用户提出的问题需要从多个资源中推断答案，而文档中又没有预先存在的目标答案时，生成式质量保证模型就能派上用场。不过，这些模型的计算成本可能很高，而且需要大量数据来进行与领域相关的训练，因此在某些情况下可能不太实用，尽管这种方法对处理域外问题特别有价值。</p><p>另一方面，当用户就特定主题提出问题，而实际答案就在文档中时，就可以使用提取式质量保证模型。这些模型直接从源文档中提取答案，提供透明、可验证的结果，对于希望提供简单高效的问题解答方式的企业或组织来说，是一种更实用的选择。</p><p>下面的示例演示了如何使用预先训练好的抽取式质量保证模型从给定上下文中抽取答案，该模型<a href="https://huggingface.co/deepset/minilm-uncased-squad2">可在 Hugging Face 上获得</a>，并已部署到 Elasticsearch 中：</p>POST _ml/trained_models/deepset__minilm-uncased-squad2/deployment/_infer
{
    "docs": [{"text_field": "Canvas is a data visualization and presentation application within Kibana. With Canvas, live data can be pulled directly from Elasticsearch and combined with colors, images, text, and other customized options to create dynamic, multi-page displays."}],
    "inference_config": {"question_answering": {"question": "What is Kibana Canvas?"}}
}


{
  "predicted_value": "a data visualization and presentation application",
  "start_offset": 10,
  "end_offset": 59,
  "prediction_probability": 0.28304219431376443
}
<p><a href="https://www.elastic.co/guide/en/machine-learning/current/ml-nlp-deploy-models.html">部署训练有素的模型。</a></p><p><a href="https://www.elastic.co/guide/en/machine-learning/current/ml-nlp-ner-example.html#ex-ner-ingest">将模型添加到推理摄取管道中。</a></p><p>处理用户查询和检索信息的方法多种多样，在处理非结构化数据时，使用多种语言模型和数据源不失为一种有效的选择。为了说明这一点，我们以一个聊天机器人的数据处理为例，该聊天机器人会根据从选定文档中提取的数据来回答询问。</p><h2>聊天机器人数据处理：NLP 和向量搜索</h2><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blta418a9c54bb16cf9/6a17d7975772624b371bca43/c2d1a2f110e937b1d3e5df0d5caac3c906c98fb0-1440x748.png" alt="" /><p>如上图所示，聊天机器人的数据处理可分为三个部分：</p><ul><li><p><strong>矢量处理：</strong>这部分将文档转换为矢量表示。</p></li><li><p><strong>用户输入处理：</strong>这部分从用户查询中提取相关信息，并执行语义搜索和混合检索。</p></li><li><p><strong>优化：</strong>这部分包括监控，对于确保聊天机器人的可靠性、最佳性能和良好的用户体验至关重要。</p></li></ul><h2>矢量处理</h2><p>对于<strong>处理</strong>部分，第一步是确定每个文档的组成部分，然后将每个元素转换为矢量表示法；这些表示法可以为多种数据格式创建。</p><p>有多种方法可用于计算嵌入，包括预训练模型和库。</p><p>值得注意的是，在这些表征上进行搜索和检索的有效性取决于现有数据以及所用方法的质量和相关性。</p><p>在计算向量时，它们会以<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/dense-vector.html">dense_vector</a>字段类型存储在 Elasticsearch 中。</p>PUT &lt;target&gt;
{
  "mappings": {
    "properties": {
      "doc_part_vector": {
        "type": "dense_vector",
        "dims": 3
      },
      "doc_part" : {
        "type" : "keyword"
      }
    }
  }
}
<h2>聊天机器人用户输入处理</h2><p>对于<strong>用户</strong>来说，在收到问题后，最好先从中提取所有可能的信息，然后再继续提问。这有助于理解用户的意图，在这种情况下，我们使用<a href="https://huggingface.co/dslim/bert-base-NER">命名实体识别模型（NER）</a>来帮助理解用户的意图。NER 是将命名实体识别和分类为预定义实体类别的过程。</p>POST _ml/trained_models/dslim__bert-base-ner/deployment/_infer
{
  "docs": { "text_field": "How many people work for Elastic?"}
}


{
  "predicted_value": "How many people work for [Elastic](ORG&amp;Elastic)?",
  "entities": [
    {
      "entity": "Elastic",
      "class_name": "ORG",
      "class_probability": 0.4993975435876747,
      "start_pos": 25,
      "end_pos": 32
    }
  ]
}
<p>虽然这不是必要步骤，但通过使用结构化数据或上述或其他 NLP 模型结果对用户的查询进行分类，我们可以使用<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/knn-search.html#knn-search-filter-example">过滤器</a>对 kNN 搜索进行限制。这有助于减少需要处理的数据量，从而提高性能和准确性。</p>    "filter": {
      "term": {
        "org": "Elastic"
      }
    }
<h2>语义搜索和混合检索</h2><p>由于提示源于用户询问，而聊天机器人需要处理人类语言的多变性和模糊性，因此<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/knn-search.html#semantic-search">语义搜索</a>非常适合。在 Elasticsearch 中，只要将查询字符串和<a href="https://huggingface.co/sentence-transformers/msmarco-MiniLM-L-12-v3">嵌入模型</a>的 ID 传递到 query_vector_builder 对象中，就能在一个步骤中执行语义搜索。这将对查询进行矢量化，并执行 kNN<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html">搜索</a>，以检索与查询含义最接近的前 k 个匹配项：</p>POST /&lt;target&gt;/_search
{
  "knn": {
    "field": "doc_part_vector",
    "k": 5,
    "num_candidates": 20,
    "query_vector_builder": {
      "text_embedding": {
        "model_id": "&lt;text-embedding-model-id&gt;",
        "model_text": "&lt;query_string&gt;"
      }
    }
  }
 }
<p><a href="https://www.elastic.co/guide/en/machine-learning/8.7/ml-nlp-text-emb-vector-search-example.html">端到端示例：如何部署文本嵌入模型并将其用于语义搜索。</a>Elasticsearch 使用 Okapi BM25 的 Lucene 实现（一种<strong>稀疏模型</strong>）对文本查询进行相关性排序，而<strong>密集模型</strong>则用于<strong>语义搜索</strong>。为了<strong>综合矢量</strong>匹配和文本查询匹配的<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/knn-search.html#_combine_approximate_knn_with_other_features"><strong>优势</strong></a> <strong>，</strong>可以执行<strong>混合检索</strong>：</p>POST &lt;target&gt;/_search
{
  "query": {
          "match": {
            "content": {
              "query": "&lt;query_string&gt;"
            }
        }
  },
  "knn": {
    "field": "doc_part_vector",
    "query_vector_builder": {
      "text_embedding": {
    "model_id": "&lt;text-embedding-model-id&gt;",
     "model_text": "&lt;query_string&gt;"
      }
    },
    "filter": {
      "term": {
        "org": "Elastic"
      }
    }
  }
}
<h3>将稀疏模型和密集模型相结合，往往能获得最佳结果</h3><p>稀疏模型通常在简短查询和特定术语方面表现更佳，而密集模型则利用上下文和关联。如果您想进一步了解这些方法如何相互比较和互补，我们在此将 BM25 与两个经过专门检索训练的密集模型进行比较。</p><p>最相关的结果通常可能是给用户的第一个答案，分数是一个用来确定返回文档<strong>相关性的</strong>数字。</p><h2>优化聊天机器人</h2><p>为了帮助改善聊天机器人的用户体验、性能和可靠性，除了应用混合评分外，您还可以采用以下方法：<strong>情感分析：</strong>为了在对话过程中了解用户的评论和反应，您可以采用<a href="https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english">情感分析模型</a>：</p>POST _ml/trained_models/distilbert-base-uncased-finetuned-sst-2-english/deployment/_infer
{
  "docs": { "text_field": "That was not my question!"}
}


{
  "predicted_value": "NEGATIVE",
  "prediction_probability": 0.980080439016437
}
<p><a href="https://www.elastic.co/blog/chatgpt-elasticsearch-openai-meets-private-data"><strong>GPT 的功能</strong></a> <strong>：</strong>作为增强整体体验的另一种方法，您可以将 Elasticsearch 的搜索相关性与 OpenAI 的 GPT 问题解答功能相结合，利用<a href="https://platform.openai.com/docs/guides/chat">聊天完成 API</a>返回给用户由模型生成的回复，并将这些前 k 个文档作为上下文。<em>提示："回答此问题&lt;user_question&gt; 仅使用此文档&lt;top_search_result&gt;"</em></p><p><strong>可观察性：</strong>确保任何聊天机器人的性能都至关重要，而监控是实现这一目标的重要组成部分。除了记录聊天机器人的互动日志，跟踪响应时间、延迟和其他相关的聊天机器人指标也很重要。<a href="https://www.elastic.co/blog/monitor-openai-api-gpt-models-opentelemetry-elastic">Elastic Observability</a>工具使您能够收集和分析这些信息。</p><h2>总结</h2><p>这篇博文介绍了什么是 NLP 和矢量搜索，并举例说明了聊天机器人如何通过考虑从文档的矢量表示中提取的数据来回答用户的询问。</p><p>如图所示，利用 NLP 和矢量搜索，聊天机器人能够执行结构化、目标数据之外的复杂任务。这包括使用多种数据源和格式作为上下文进行推荐和回答特定产品或业务相关查询，同时提供个性化的用户体验。</p><p>使用案例包括提供客户服务，协助客户进行咨询；帮助开发人员进行查询，提供逐步指导，提出建议，甚至自动执行任务。根据目标和现有数据，还可以利用其他模型和方法来取得更好的效果，改善整体用户体验。</p><p>下面是一些关于该主题的链接，可能会对您有所帮助：</p><ol><li><p><a href="https://www.elastic.co/blog/how-to-deploy-natural-language-processing-nlp-getting-started">如何部署自然语言处理 (NLP)：入门</a></p></li><li><p><a href="https://www.elastic.co/blog/overview-image-similarity-search-in-elastic">Elasticsearch 中的图像相似性搜索概述</a></p></li><li><p><a href="https://www.elastic.co/blog/chatgpt-elasticsearch-openai-meets-private-data">ChatGPT 和 Elasticsearch：OpenAI 与私人数据的结合</a></p></li><li><p><a href="https://www.elastic.co/blog/monitor-openai-api-gpt-models-opentelemetry-elastic">使用 OpenTelemetry 和 Elastic 监测 OpenAI API 和 GPT 模型</a></p></li><li><p><a href="https://www.elastic.co/blog/why-technology-leaders-need-vector-search">IT 领导者需要矢量搜索来改善搜索体验的 5 个原因</a></p></li></ol><p>通过在 Elasticsearch 中集成 NLP 和本地矢量搜索，您可以利用其速度、可扩展性和搜索功能来创建高效、有效的聊天机器人，从而能够处理大量结构化或非结构化数据。</p><p>准备好开始了吗？开始<a href="https://cloud.elastic.co/registration?onboarding_token=vectorsearch&amp;cta=cloud-registration&amp;tech=trial&amp;plcmt=article%20content&amp;pg=search-labs">免费试用弹性云</a>。</p><p><em>在本博文中，我们可能会使用或提及第三方生成式人工智能工具，这些工具由其各自所有者拥有和运营。Elastic对第三方工具没有任何控制权，我们对其内容、操作或使用不承担任何责任或义务，对您使用此类工具可能造成的任何损失或损害也不承担任何责任或义务。在使用人工智能工具处理个人、敏感或机密信息时，请务必谨慎。您提交的任何数据都可能用于人工智能培训或其他目的。我们不保证您所提供信息的安全性或保密性。在使用任何人工智能生成工具之前，您都应熟悉其隐私惯例和使用条款。</em></p><p><em>Elastic、Elasticsearch 和相关标记是 Elasticsearch N.V. 在美国和其他国家的商标、徽标或注册商标。所有其他公司和产品名称均为其各自所有者的商标、徽标或注册商标。</em></p>]]></content:encoded>
    <link>https://www.elastic.co/search-labs/blog/enhancing-chatbot-capabilities-with-nlp-and-vector-search-in-elasticsearch</link>
    <guid isPermaLink="true">https://www.elastic.co/search-labs/blog/enhancing-chatbot-capabilities-with-nlp-and-vector-search-in-elasticsearch</guid>
    <category><![CDATA[向量数据库]]></category>
    <dc:creator><![CDATA[Priscilla Parodi]]></dc:creator>
    <enclosure url="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt5c545fc80b6d79d6/6a170214839dfad776dcfd6f/d968e646240cd3ef7c79b5124d562a5f951d812b-1440x840.png" length="0" type="image/png"/>
    <pubDate>Wed, 21 Jun 2023 00:00:00 GMT</pubDate>
  </item>
  </channel>
</rss>