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计数内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
使用Pytorch Geometric进行链接预测的实现代码
PyTorch Geometric (PyG)是构建图神经网络模型和实验各种图卷积的主要工具,在本文中我们将通过链接预测来对其进行介绍,文中有详细的代码示例供大家参考,需要的朋友可以参考下2023-10-10
使用python批量读取word文档并整理关键信息到excel表格的实例
今天小编就为大家分享一篇使用python批量读取word文档并整理关键信息到excel表格的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2018-11-11


最新评论