Elasticsearch:使用查询规则(query rules)进行搜索

这篇具有很好参考价值的文章主要介绍了Elasticsearch:使用查询规则(query rules)进行搜索。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

在之前的文章 “Elasticsearch 8.10 中引入查询规则 - query rules”,我们详述了如何使用 query rules 来进行搜索。这个交互式笔记本将向你介绍如何使用官方 Elasticsearch Python 客户端来使用查询规则。 你将使用 query rules API 将查询规则存储在 Elasticsearch 中,并使用 rule_query 查询它们。

安装

安装 Elasticsearch 及 Kibana

如果你还没有安装好自己的 Elasticsearch 及 Kibana,那么请参考一下的文章来进行安装:

  • 如何在 Linux,MacOS 及 Windows 上进行安装 Elasticsearch

  • Kibana:如何在 Linux,MacOS 及 Windows 上安装 Elastic 栈中的 Kibana

在安装的时候,请选择 Elastic Stack 8.x 进行安装。在安装的时候,我们可以看到如下的安装信息:

Elasticsearch:使用查询规则(query rules)进行搜索,Elasticsearch,Elastic,elasticsearch,大数据,搜索引擎,全文检索,人工智能,python

环境变量

在启动 Jupyter 之前,我们设置如下的环境变量:

export ES_USER="elastic"
export ES_PASSWORD="xnLj56lTrH98Lf_6n76y"
export ES_ENDPOINT="localhost"

请在上面修改相应的变量的值。这个需要在启动 jupyter 之前运行。

拷贝 Elasticsearch 证书

我们把 Elasticsearch 的证书拷贝到当前的目录下:

$ pwd
/Users/liuxg/python/elser
$ cp ~/elastic/elasticsearch-8.12.0/config/certs/http_ca.crt .
$ ls http_ca.crt 
http_ca.crt

安装 Python 依赖包

python3 -m pip install -qU elasticsearch load_dotenv

准备数据

我们在项目当前的目录下创建如下的数据文件:

query-rules-data.json 

[
  {
    "id": "us1",
    "content": {
      "name": "PureJuice Pro",
      "description": "PureJuice Pro: Experience the pinnacle of wireless charging. Blending rapid charging tech with sleek design, it ensures your devices are powered swiftly and safely. The future of charging is here.",
      "price": 15.00,
      "currency": "USD",
      "plug_type": "B",
      "voltage": "120v"
    }
  },
  {
    "id": "uk1",
    "content": {
      "name": "PureJuice Pro - UK Compatible",
      "description": "PureJuice Pro: Redefining wireless charging. Seamlessly merging swift charging capabilities with a refined aesthetic, it guarantees your devices receive rapid and secure power. Welcome to the next generation of charging.",
      "price": 20.00,
      "currency": "GBP",
      "plug_type": "G",
      "voltage": "230V"
    }
  },
  {
    "id": "eu1",
    "content": {
      "name": "PureJuice Pro - Wireless Charger suitable for European plugs",
      "description": "PureJuice Pro: Elevating wireless charging. Combining unparalleled charging speeds with elegant design, it promises both rapid and dependable energy for your devices. Embrace the future of wireless charging.",
      "price": 18.00,
      "currency": "EUR",
      "plug_type": "C",
      "voltage": "230V"
    }
  },
  {
    "id": "preview1",
    "content": {
      "name": "PureJuice Pro - Pre-order next version",
      "description": "Newest version of the PureJuice Pro wireless charger, coming soon! The newest model of the PureJuice Pro boasts a 2x faster charge than the current model, and a sturdier cable with an eighteen month full warranty. We also have a battery backup to charge on-the-go, up to two full charges. Pre-order yours today!",
      "price": 36.00,
      "currency": "USD",
      "plug_type": ["B", "C", "G"],
      "voltage": ["230V", "120V"]
    }
  }
]

创建应用并展示

我们在当前的目录下打入如下的命令来创建 notebook:

$ pwd
/Users/liuxg/python/elser
$ jupyter notebook

导入包及连接到 Elasticsearch

from elasticsearch import Elasticsearch
from dotenv import load_dotenv
import os

load_dotenv()
 
openai_api_key=os.getenv('OPENAI_API_KEY')
elastic_user=os.getenv('ES_USER')
elastic_password=os.getenv('ES_PASSWORD')
elastic_endpoint=os.getenv("ES_ENDPOINT")
 
url = f"https://{elastic_user}:{elastic_password}@{elastic_endpoint}:9200"
client = Elasticsearch(url, ca_certs = "./http_ca.crt", verify_certs = True)
 
print(client.info())

Elasticsearch:使用查询规则(query rules)进行搜索,Elasticsearch,Elastic,elasticsearch,大数据,搜索引擎,全文检索,人工智能,python

索引一些测试数据

我们的客户端已设置并连接到我们的 Elastic 部署。 现在我们需要一些数据来测试 Elasticsearch 查询的基础知识。 我们将使用具有以下字段的小型产品索引:

  • name
  • description
  • price
  • currency
  • plug_type
  • voltage

运行以下命令上传一些示例数据:

import json

# Load data into a JSON object
with open('query-rules-data.json') as f:
   docs = json.load(f)

operations = []
for doc in docs:
    operations.append({"index": {"_index": "products_index", "_id": doc["id"]}})
    operations.append(doc["content"])
client.bulk(index="products_index", operations=operations, refresh=True)

Elasticsearch:使用查询规则(query rules)进行搜索,Elasticsearch,Elastic,elasticsearch,大数据,搜索引擎,全文检索,人工智能,python

我们可以在 Kibana 中进行查看:

Elasticsearch:使用查询规则(query rules)进行搜索,Elasticsearch,Elastic,elasticsearch,大数据,搜索引擎,全文检索,人工智能,python

搜索测试数据

首先,让我们搜索数据寻找 “reliable wireless charger.”。

在搜索数据之前,我们将定义一些方便的函数,将来自 Elasticsearch 的原始 JSON 响应输出为更易于理解的格式。

def pretty_response(response):
    if len(response['hits']['hits']) == 0:
        print('Your search returned no results.')
    else:
        for hit in response['hits']['hits']:
            id = hit['_id']
            score = hit['_score']
            name = hit['_source']['name']
            description = hit['_source']['description']
            price = hit["_source"]["price"]
            currency = hit["_source"]["currency"]
            plug_type = hit["_source"]["plug_type"]
            voltage = hit["_source"]["voltage"]
            pretty_output = (f"\nID: {id}\nName: {name}\nDescription: {description}\nPrice: {price}\nCurrency: {currency}\nPlug type: {plug_type}\nVoltage: {voltage}\nScore: {score}")
            print(pretty_output)

def pretty_ruleset(response):
    print("Ruleset ID: " + response['ruleset_id'])
    for rule in response['rules']:
        rule_id = rule['rule_id']
        type = rule['type']
        print(f"\nRule ID: {rule_id}\n\tType: {type}\n\tCriteria:")
        criteria = rule['criteria']
        for rule_criteria in criteria:
            criteria_type = rule_criteria['type']
            metadata = rule_criteria['metadata']
            values = rule_criteria['values']
            print(f"\t\t{metadata} {criteria_type} {values}")
        ids = rule['actions']['ids']
        print(f"\tPinned ids: {ids}")

接下来,进行搜索

不使用 query rules 的正常搜索

response = client.search(index="products_index", query={
    "multi_match": {
        "query": "reliable wireless charger for iPhone",
        "fields": [ "name^5", "description" ]
    }
})

pretty_response(response)

Elasticsearch:使用查询规则(query rules)进行搜索,Elasticsearch,Elastic,elasticsearch,大数据,搜索引擎,全文检索,人工智能,python

创建 query rules

我们分别假设,我们知道我们的用户来自哪个国家/地区(可能通过 IP 地址或登录的用户帐户信息进行地理位置定位)。 现在,我们希望创建查询规则,以便当人们搜索包含短语 “wireless charger (无线充电器)” 的任何内容时,根据该信息增强无线充电器的性能。

client.query_ruleset.put(ruleset_id="promotion-rules", rules=[
    {
      "rule_id": "us-charger",
      "type": "pinned",
      "criteria": [
        {
          "type": "contains",
          "metadata": "my_query",
          "values": ["wireless charger"]
        },
        {
          "type": "exact",
          "metadata": "country",
          "values": ["us"]
        }
      ],
      "actions": {
        "ids": [
          "us1"
        ]
      }
    },
    {
      "rule_id": "uk-charger",
      "type": "pinned",
      "criteria": [
        {
          "type": "contains",
          "metadata": "my_query",
          "values": ["wireless charger"]
        },
        {
          "type": "exact",
          "metadata": "country",
          "values": ["uk"]
        }
      ],
      "actions": {
        "ids": [
          "uk1"
        ]
      }
    }
  ])

为了使这些规则匹配,必须满足以下条件之一:

  • my_query 包含字符串 “wireless charger” 并且 country “us”
  • my_query 包含字符串 “wireless charger” 并且 country 为 “uk”

我们也可以使用 API 查看我们的规则集(使用另一个 Pretty_ruleset 函数以提高可读性):

response = client.query_ruleset.get(ruleset_id="promotion-rules")
pretty_ruleset(response)

Elasticsearch:使用查询规则(query rules)进行搜索,Elasticsearch,Elastic,elasticsearch,大数据,搜索引擎,全文检索,人工智能,python

response = client.search(index="products_index", query={
      "rule_query": {
          "organic": {
              "multi_match": {
                  "query": "reliable wireless charger for iPhone",
                  "fields": [ "name^5", "description" ]
              }
          },
          "match_criteria": {
            "my_query": "reliable wireless charger for iPhone",
            "country": "us"
          },
          "ruleset_id": "promotion-rules"
      }
})

pretty_response(response)

Elasticsearch:使用查询规则(query rules)进行搜索,Elasticsearch,Elastic,elasticsearch,大数据,搜索引擎,全文检索,人工智能,python

整个 notebook 的源码可以在地址下载:https://github.com/liu-xiao-guo/semantic_search_es/blob/main/search_using_query_rules.ipynb文章来源地址https://www.toymoban.com/news/detail-831900.html

到了这里,关于Elasticsearch:使用查询规则(query rules)进行搜索的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

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

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

相关文章

  • Elasticsearch:使用 query_string 查询的短语及模糊查询

    在我之前的文章系列里,我详细描述了 query_string 的一些功能: Elasticsearch: query_string 查询 Elasticsearch:以更简单的方式编写具有逻辑条件的 Elasticsearch 查询 - query_string Elasticsearch:理解 query_string 和 simple_query_string 查询 在今天的文章中,我们来聊聊 query_string 中的一下特殊查询

    2024年02月09日
    浏览(40)
  • 【ElasticSearch-基础篇】ES高级查询Query DSL术语级别查询并结合springboot使用

    Elasticsearch 提供了基于 JSON 的完整 Query DSL(Domain Specific Language)来定义查询。 因Query DSL是利用Rest API传递JSON格式的请求体(RequestBody)数据与ES进行交互,所以我们在使用springboot的时候也可以很方便的进行集成,本文主要讲述的就是使用springboot实现各类DSL的语法查询。 Elastics

    2024年02月01日
    浏览(46)
  • 解码 Elasticsearch 查询 DSL:利用 Elasticsearch 中的 has_child 和 has_parent 查询进行父子文档搜索

    今天,让我们深入研究 has_child 查询和 has_parent 查询,这将帮助我们将 2 个不同的文档组合到一个索引中,从而使我们能够将它们与关系关联起来。 这样做会对我们搜索相关文档时有很大帮助。 在使用 has_child 及 has_parent 这种关系时,我们必须使用 join 数据类型。更多有关

    2024年02月02日
    浏览(33)
  • Elasticsearch Boolean Query查询介绍

    前言 ES 和 Solr 的底层都是基于Apache Lucene 实现,bool 查询的底层实现是Lucene 的 BooleanQuery,其可以组合多个子句查询,类似 SQL 语句里面的 OR 查询。 查询介绍 在 ES 里面 Boolean 查询封装了 4 种 API 接口能力,可以单独使用,也可以组合使用,总结如下: 函数 描述 must query 关键

    2024年02月13日
    浏览(40)
  • elasticsearch 笔记二:搜索DSL 语法(搜索API、Query DSL)

    从索引 tweet 里面搜索字段 user 为 kimchy 的记录 从索引 tweet,user 里面搜索字段 user 为 kimchy 的记录 从所有索引里面搜索字段 tag 为 wow 的记录 说明:搜索的端点地址可以是多索引多 mapping type 的。搜索的参数可作为 URI 请求参数给出,也可用 request body 给出 URI 搜索方式通过 URI

    2024年02月04日
    浏览(45)
  • ElasticSearch级查询Query DSL上

    目录 ES高级查询Query DSL match_all 返回源数据_source 返回指定条数size 分页查询fromsize 指定字段排序sort 术语级别查询 Term query术语查询 Terms Query多术语查询 exists query ids query range query范围查询 prefix query前缀查询 wildcard query通配符查询 fuzzy query模糊查询        ES中提供了一种强大

    2024年02月20日
    浏览(49)
  • ElasticSearch Index查询(Query DSL)

    先贴一个Query DSL的官方文档:https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl.html 我平时喜欢查看官方文档,了解数据查询和存储方面的性能优化点,下面是积累的脚本分享。 查询语句格式 查询类型:match_all,match,term,range,fuzzy,bool 等等 查询条件:查询条件会根

    2024年02月07日
    浏览(40)
  • Elasticsearch复合查询之Boosting Query

    前言 ES 里面有 5 种复合查询,分别是: Boolean Query Boosting Query Constant Score Query Disjunction Max Query Function Score Query Boolean Query在之前已经介绍过了,今天来看一下 Boosting Query 用法,其实也非常简单,总结起来就一句话,对不期待的查询进行相关性降分。 Boost 加权机制底层

    2024年02月12日
    浏览(37)
  • vue中的rules表单校验规则使用方法 :rules=“rules“

    :ref=\\\"dataForm\\\"        // 提交表单时进行校验 :rules=\\\"rules\\\"            // return 下的校验规则 :model=\\\"userForm\\\"  // 绑定表单的值 点击提交时,会先对表单的值进行校验判断,校验通过后,再进行后续操作。 el-form-item 里面使用 prop 属性绑定规则 el-form-item label=\\\"充值金额\\\"  prop=\\\"amo

    2024年02月05日
    浏览(39)
  • Elasticsearch 查询之Function Score Query

    前言 ES 的主查询评分模式分为两种,是信息检索领域的重要算法: TF-IDF 算法 和 BM25 算法。 Elasticsearch 从版本 5.0 开始引入了 BM25 算法作为默认的文档评分(relevance scoring)算法。在此之前,Elasticsearch 使用的是 TF-IDF 算法作为默认的文档评分算法。从版本 5.0 起,BM25 算法取代

    2024年02月12日
    浏览(35)

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

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

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

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

二维码1

领取红包

二维码2

领红包