ES中的模糊查询

发布时间 2023-12-06 16:03:53作者: 做时间的好朋友

1.如果目标字段类型是keyword,可以用wildcard 语法进行查询

{
                    "wildcard":{
                        "log_content":{
                            "wildcard":"*aaa*",
                            "boost":1
                        }
                    }
 }

配合使用

{
    "query":{
        "bool":{
            "must":[
                {
                    "terms":{
                        "resourceId":[
                            "es-465dilnawj"
                        ],
                        "boost":1
                    }
                },
                {
                    "wildcard":{
                        "log_content":{
                            "wildcard":"*aaa*",
                            "boost":1
                        }
                    }
                },
                {
                    "range":{
                        "time":{
                            "from":1701844550000,
                            "to":1701844554000,
                            "include_lower":true,
                            "include_upper":true,
                            "boost":1
                        }
                    }
                },
                {
                    "term":{
                        "slowLogType":{
                            "value":"ES_INDEX",
                            "boost":1
                        }
                    }
                }
            ],
            "adjust_pure_negative":true,
            "boost":1
        }
    },
    "sort":[
        {
            "time":{
                "order":"desc"
            }
        }
    ]
}

java代码

QueryBuilders.wildcardQuery("log_detail.index","*" + param.getIndex() + "*")

2.如果目标字段是text类型,模糊查询使用match查询

{
          "match": {
            "log_content": {
              "query": "天"
            }
          }
        }

配合使用

{
  "query": {
    "bool": {
      "must": [
        {
          "terms": {
            "resourceId": [
              "es-465dilnawj"
            ],
            "boost": 1
          }
        },
        {
          "match": {
            "log_content": {
              "query": "天"
            }
          }
        },
        {
          "range": {
            "time": {
              "from": 1701844550000,
              "to": 1701844554000,
              "include_lower": true,
              "include_upper": true,
              "boost": 1
            }
          }
        },
        {
          "term": {
            "slowLogType": {
              "value": "ES_INDEX",
              "boost": 1
            }
          }
        }
      ],
      "adjust_pure_negative": true,
      "boost": 1
    }
  },
  "sort": [
    {
      "time": {
        "order": "desc"
      }
    }
  ]
}

java代码

QueryBuilders.matchQuery("log_content",param.getLogContent())