首页 > 其他分享 >修正es查询里的字段类型是keyword的query

修正es查询里的字段类型是keyword的query

时间:2023-04-07 23:24:02浏览次数:31  
标签:keyword value field match key query es

def convert_query(query):
    """
    Convert Elasticsearch query to use keyword and text fields appropriately
    """
    if isinstance(query, dict):
        for key, value in query.items():
            if key in ["term", "terms", 'range']:
                new_value = dict()
                for k, v in value.items():
                    if not k.endswith(".keyword"):
                        k = f"{k}.keyword"
                    new_value.update({k: v})
                query[key] = new_value
            elif key in ["match", "match_phrase", "match_phrase_prefix"]:
                new_value = dict()
                for k, v in value.items():
                    if k.endswith(".keyword"):
                        k = k[:-len(".keyword")]
                    new_value.update({k: v})
                query[key] = new_value
            elif key == "multi_match":
                new_fields = list()
                fields = query[key].get("fields", [])
                for field in fields:
                    if field.endswith(".keyword"):
                        field = field[:-len(".keyword")]
                    new_fields.append(field)
                query[key] = {
                    "query": query[key].get("query"),
                    "fields": new_fields
                }
            elif key == "exists":
                field = query[key].get("field")
                query[key] = {"field": field if field.endswith(".keyword") else f"{field}.keyword"}
            else:
                query[key] = convert_query(value)
    elif isinstance(query, list):
        query = [convert_query(q) for q in query]
    return query


query = {
    "query": {
        "bool": {
            "must": [
                {
                    "term": {
                        "my_field": "some_value"
                    }
                },
                {
                    "terms": {
                        "my_field1": ["some_value"]
                    }
                },
                {
                    "match": {
                        "my_text_field.keyword": "some text to match"
                    }
                },
                {"match_phrase": {"my_text_field.keyword": "some text to match"}},
                {"match_phrase_prefix": {"my_text_field.keyword": "some text to"}},
                {
                    "multi_match": {
                        "query": "full text search",
                        "fields": ["title.keyword", "body.keyword"]
                    }
                },
                {
                    "range": {
                        "age": {
                            "gte": 20,
                            "lt": 30
                        }
                    }
                },
                {"exists": {"field": "title"}}

            ],
            "filter": {
                "term": {
                    "my_other_field": "other_value"
                }
            }
        }
    }
}

converted_query = convert_query(query)

print(converted_query)

  

标签:keyword,value,field,match,key,query,es
From: https://www.cnblogs.com/navysummer/p/17297668.html

相关文章

  • Cesium案例(八) Terrain
    第一步正常建viewer,需要注意的是官网例子属性值比较老,最新版本的属性值有所差异,全copy官网会无法运行,提示函数未定义。第一处差异官网: 1constviewer=newCesium.Viewer("cesiumContainer",{2terrain:Cesium.Terrain.fromWorldTerrain({3requestWaterMask:t......
  • codeforces 1804D Accommodation
    https://codeforces.com/problemset/problem/1804/D解题思路每个楼层是独立的,考虑怎么解决一层就可以了。求最大值就是尽量避免1和1合并,也就是尽量在不存在连续1的子序列中进行合并,如果还有需要合并的就只能用1和1合并。求最小值就是尽量合并1和1。由于只需要输出最大最小值,所......
  • 【调试】kprobes(二)使用方法
    前言上一节介绍了kprobe的基本概念,下面我们将使用几个具体的例子,看下kprobe在实际使用中有那些应用场景。kprobe内核的samples/kprobe目录下有kprobe相关的例子,我们以这些例子为基础,简单修改下。查看函数的入参我们所有的例子都是探测do_sys_open()或者_do_fork(),以下是内核......
  • 【调试】kprobes(一)基本概念
    简介开发人员在内核或者模块的调试过程中,往往会需要要知道其中的一些函数有无被调用、何时被调用、执行是否正确以及函数的入参和返回值是什么等等。比较简单的做法是在内核代码对应的函数中添加日志打印信息,但这种方式往往需要重新编译内核或模块,重新启动设备之类的,操作较为复......
  • Educational Codeforces Round 146 (Rated for Div. 2)
    A.Coins#include<bits/stdc++.h>usingnamespacestd;#defineintlonglongintread(){intx=0,f=1,ch=getchar();while((ch<'0'||ch>'9')&&ch!='-')ch=getchar();if(ch......
  • R语言EG(Engle-Granger)两步法协整检验、RESET、格兰杰因果检验、VAR模型分析CPI和PPI
    全文链接:http://tecdat.cn/?p=31108最近我们被客户要求撰写关于VAR模型的研究报告,包括一些图形和统计输出。作为衡量通货膨胀的基本指标,消费者价格指数CPI和生产者价格指数PPI的作用关系与传导机制一直是宏观经济研究的核心问题。对此问题的研究显然具有重要的学术价值与现实意......
  • 【题解】CF472G Design Tutorial: Increase the Constraints
    《正解分块+FFT跑1min,__builtin_popcount暴力跑10s》《没人写正解,CF也不卡》思路正解:分块+FFT乱搞:__builtin_popcount首先我们知道哈明距离可以用一种\(O(|字符集||S|)\)的算法求。具体考虑枚举字符集中的每一个字符,将两个串中是该字符的位置看作\(1\),不是该字......
  • Serilog.Sinks.Elasticsearch 写username到 ES失败
    Usingthelib:Serilog.Sinks.ElasticsearchandECS-dotnet whichprovidetheecsformat,wecanwritelogintoesinECSformat.Ihavebeenabletooveralllinktrace, now,Iwanttorecordtheusernameifuserhaslogged.Astonoshingly,sometime,itwor......
  • AtCoder ABC286 C - Chinese Restaurant
    AtCoderABC286C-ChineseRestaurant题目描述有\(N\)个人从\(0\)开始编号,按逆时针顺序间隔均匀地坐在转盘周围。在开始时,第\(p_i\)盘菜在第\(i\)个人的前面。现在,你可以进行以下操作\(0\)次或多次。将转盘逆时针旋转\(\dfrac{1}{N}\)圈。也就是说,旋转前......
  • 994. Rotting Oranges[Medium]
    994.RottingOrangesYouaregivenanmxngridwhereeachcellcanhaveoneofthreevalues:0representinganemptycell,1representingafreshorange,or2representingarottenorange.Everyminute,anyfreshorangethatis4-directionallyadjacen......