ES的查询语法

ES的查询语法

   小樱     2022年9月3日 21:14     792    

1、统计匹配值的数量

POST gateway_accesslog_*/_count

{

  "query": {

    "match": {

      "requestURI": "/dfdfdfdfd"

    }

  }

}


结果

{

  "count" : 8,

  "_shards" : {

    "total" : 62,

    "successful" : 62,

    "skipped" : 0,

    "failed" : 0

  }

}

count字段就是查询到的数量


2、term、match、bool

(1)查询所有

{

  "query": {

    "match_all": {}

  }

  "size": 1000

}


(2)match查询

在所有包含gateway_accesslog_的索引中去查询

POST gateway_accesslog_*/_search

{

  "query": {

    "match": {

      "requestURI": "/dfdfdfdfd"

    }

  },

  "sort": {

    "@timestamp": "desc"

  },

  "size": 1000

}

match查询的如果是text类型,则可以分词处理

分词测试

GET /_analyze

{

  "text":"/api/v1.0/userAuth/loginAccount"

}


term查询

GET gateway_accesslog_2022.10.18/_search

{

  "query": {

    "term": {

      "statusCode": {

        "value": 200

      }

    }

  }

}

这种查询是用来查询非text字段的匹配,这个是精确的匹配


查询所有的并按照timestamp进行排序

GET syslog_2022.09.06/_search

{

  "query":{

    "match_all":{}

  },

  "sort":[

      {"@timestamp":{

        "order": "desc"

        }

      }

    ]

}


(3)bool

bool包含四种子语句

must,filter,should,must_not

must 对应mysql的 and a=

filter 对应mysql的 and a=

should 对应mysql的 or a=

must not 对应mysql的 and a!=

must:文档必须匹配,该选项下的查询条件,相当于逻辑运算的 AND,且参与文档相关度的评分。

should:文档可以匹配 should 选项下的查询条件也可以不匹配,相当于逻辑运算的 OR,且参与文档相关度的评分。

must_not:与 must 相反,匹配该选项下的查询条件的文档不会被返回;需要注意的是,must_not 语句不会影响评分,它的作用只是将不相关的文档排除。

filter:和 must 一样,匹配 filter 选项下的查询条件的文档才会被返回,但是 filter 不评分,只起到过滤功能,与 must_not 相反。


取出status_code为404的doc

GET accesslog_*/_search

{

  "query": {

    "bool": {

      "must": [

        {

          "term": {

              "status_code": "404"

          }

        }

      ]

    }

  }

}

GET access_*/_search

{

  "query": {

    "bool": {

      "filter": [

        {"term": 

          {

            "status_code": "404"

          }

        }

      ]

    }

  }

}


联合match和term

GET gateway_accesslog_2022.10.18/_search

{

  "query": {

    "bool": {

      "must": [

        {

          "match": {

            "requestURI": "/api/v1.0/userAuth/loginAccount"

          }

        }

        ,

        {

          "term": {

            "statusCode": {

              "value": 200

            }

          }

        }

        ,

        {

          "term": {

            "contentLength": {

              "value": 61

            }

          }

        }

      ]

    }

  }

}


3、聚合

GET accesslog_*/_search

{

  "size": 0, 

  "aggs": {

    "URI": {

      "terms": {

        "field": "requestURI"

      }

    }

  }

}

上边这个报出

image.png

text类型的字段不可以被聚合,默认的fielddata字段是false需要将其置位true,但是会消耗较多内存。

GET accesslog_*/_search

{

  "size": 0, 

  "aggs": {

    "URI": {

      "terms": {

        "field": "statusCode"

      }

    }

  }

image.png

文章评论

0

其他文章