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關系,查詢的語句如下
# 執(zhí)行查詢
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
]
}
}
}查庫結果
# 執(zhí)行查詢并輸出結果
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計數內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
使用Pytorch Geometric進行鏈接預測的實現代碼
PyTorch Geometric (PyG)是構建圖神經網絡模型和實驗各種圖卷積的主要工具,在本文中我們將通過鏈接預測來對其進行介紹,文中有詳細的代碼示例供大家參考,需要的朋友可以參考下2023-10-10
python排序函數sort()與sorted()的區(qū)別
這篇文章主要介紹了python排序函數sort()與sorted()的區(qū)別,需要的朋友可以參考下2018-09-09
使用python批量讀取word文檔并整理關鍵信息到excel表格的實例
今天小編就為大家分享一篇使用python批量讀取word文檔并整理關鍵信息到excel表格的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-11-11

