脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|shell|

服务器之家 - 脚本之家 - Python - python+elasticsearch实现标签匹配计数操作

python+elasticsearch实现标签匹配计数操作

2024-04-23 16:24P-ShineBeam Python

这篇文章主要介绍了python+elasticsearch实现标签匹配计数操作,本文通过实例代码给大家介绍的非常详细,需要的朋友可以参考下

给定一组标签 [{“tag_id”: “1”, “value”: “西瓜”}, {“tag_id”: “1”, “value”: “苹果”}],我想精准匹配到现有的标签库中存在的标签并记录匹配成功的数量。

标签id(tag_id) 标签名(tag_name) 标签值(tag_name )
1 水果 西瓜
1 水果 苹果
1 水果 橙子
2 动物 老虎

这个步骤需要sql中的and操作,即:

es中的must条件

{
  "query": {
    "bool": {
      "must": [
          {
            "term": {
              "条件1":  "ok"
            }
          },
          {
            "term": {
              "条件2":  123
            }
          }
        ]
    }
  }
}

要同时满足条件1,条件2这个查询才会有结果。里面的term表示精准查询。

这个步骤需要sql中的or操作,即:

es中的should条件

{
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "条件1": "ok"
          }
        },
        {
          "match": {
            "条件2": "666"
          }
        }
      ]
    }
  }
}

满足条件1,条件2任意一个查询都会有结果。里面的match表示模糊查询。

查询

我需要查询给定这组标签 [{“tag_id”: “1”, “value”: “西瓜”}, {“tag_id”: “1”, “value”: “苹果”}],在现有的标签库出现的次数,这既需要tag_id和value的and关系,又需要外层的or关系,查询的语句如下

# 执行查询
query_terms = [{"tag_id": "1", "value": "西瓜"}, {"tag_id": "1", "value": "苹果"}]
query = {
    "query": {
        "bool": {
            "should": [
                        {"bool": {
                                "must": [
                                            {
                                                "term": {
                                                "value":  term['value']
                                                }
                                            },
                                            {
                                                "term": {
                                                "tag_id":  term['tag_id']
                                                }
                                            }
                                            ]
                            }} for term in query_terms
            ]
        }
    }
}

查库结果

# 执行查询并输出结果
search_result = es.search(index=index_name, body=query)
num_matches = search_result["hits"]["total"]["value"]  
print(num_matches)
if search_result["hits"]["total"]["value"] == 0:
    print("没有匹配的结果。查询条件:", query_terms)
else:
    print("查询结果:")
    for hit in search_result["hits"]["hits"]:
        print("ID:", hit["_id"], "Score:", hit["_score"], "Data:", hit["_source"])

到此这篇关于python+elasticsearch实现标签匹配计数操作的文章就介绍到这了,更多相关python elasticsearch计数内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/weixin_42045968/article/details/137834564

延伸 · 阅读

精彩推荐