python借助elasticsearch实现标签匹配计数

发布于:2024-04-20 ⋅ 阅读:(25) ⋅ 点赞:(0)

给定一组标签 [{“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"])