ES查询api

Joe's blog / 2023-08-11 / 原文

1. 查询类型

  • match 和match_phrase的区别

    match 和match_phrase查询的关键字都会被分词,match_phrase 要求查询结果中包含所有查询的分词结果,并且顺序保持一致

  • query_string

    可以匹配文档中的任意字段进行全文搜索

    • 使用复杂的语法

      {
          "query": {
              "query_string": {
                  "query": "Men -Event:Football"
              }
          }
      }
      
    • 指定查询字段request

    {
        "query": {
            "query_string": {
                "query": "keyword",
                "fields": ["field1", "field2", "field3"]
            }
        }
    }
    
  • term 查询

    对关键词进行全部匹配

2. Bool 查询

{
    "query": {
        "bool": {
            "must": [
                {
                    "match": {
                        "City": "paris"
                    }
                },
                {
                    "match": {
                        "Medal": "gold"
                    }
                }
            ],
            "should": [],
            "must_not": [],
            "filter": [
                {
                    "term": {
                        "Country": "ger"
                    }
                },
                {
                    "range": {
                        "@timestamp": {
                            "gte": "2023-06-28 13:26:27",
                            "lte": "2023-06-28 13:26:27",
                            "format": "2006-01-02 15:04:05"
                        }
                    }
                }
            ]
        }
    },
    "sort": [
        {
            "@timestamp": {
                "order": "desc"
            }
        }
    ],
    "size": 10
}

一旦指定sort 将不按照得分排序

查询关键字高亮

{
    "query": {
        "bool": {
            "must": [
                {
                    "match": {
                        "description": "文件"
                    }
                },
                 {
                    "match": {
                        "user_name": "乔"
                    }
                }
            ],
        }
    },
    "highlight": {
        "pre_tags": [
            "<span style='color:red'>"
        ],
        "post_tags": [
            "</span>"
        ],
        "fields": {
            "description": {},
            "user_name": {}
        }
    },
    "from": 1,
    "size": 10
}