elasticsearch-es search 查询

elasticsearch-es search 查询

准备

准备数据:

POST /user/_doc/1
{
  "name": "小明",
  "age": 12,
  "birth": "2020-12-11"
}

POST /user/_doc/2
{
  "name": "小西",
  "age": 25,
  "birth": "2020-07-11"
}

POST /user/_doc/3
{
  "name": "大明",
  "age": 120,
  "birth": "2020-05-10"
}

基于url


POST /user/_search?q=name:'小明'

//排序
POST /user/_search?q=name:'明'&sort=birth:asc

//_source指定返回字段
POST /user/_search?q=name:'小明'&_source=name,age

//分页
POST /user/_search?from=0&size=2

基于请求主体 query DSL

POST /user/_search
{
  "query": {
    "match_all": {}
  }
}

//分页
POST /user/_search
{
  "query": {
    "match_all": {}
  },
  "from": 1,
  "size": 2
}

//指定返回字段
POST /user/_search
{
  "query": {
    "match_all": {}
  },
  "_source": ["name", "age"]
}

//排序
POST /user/_search
{
  "query": {
    "match_all": {}
  },
  "sort": [
    {
      "birth": {
        "order": "desc"
      },
      "age": {
        "order": "desc"
      }
    }
  ]
}

filter过滤器 DSL

POST /user/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "name.keyword": "大明"
          }
        }
      ]
    }
  }
}

term精确查询

精确查询,通常用于对keyword和有精确值的字段进行查询,不会对进行查询的文本进行分词操作


POST /user/_search
{
  "query": {
    "term": {
      "name": {
        "value": "小明"
      }
    }
  }
}

//对比前一种, 前一种可以查询不到结果
POST /user/_search
{
  "query": {
    "term": {
      "name.keyword": {
        "value": "小明"
      }
    }
  }
}

// terms 查询多个词条
POST /user/_search
{
  "query": {
    "terms": {
      "name": ["小明", "小西"]
    }
  }
}

match 查询

全文搜索, 通常用于对text类型字段的查询,会对进行查询的文本先进行分词操作

bool查询

POST /user/_search
{
  "query": {
    "match": {
      "name": {
        "query": "小明 hello",
        "operator": "and"
      }
    }
  }
}

如果直接搜索 小明 hello, elasticsearch 会搜索小明 OR hello,不过修改 operator 后,会匹配同时存在这两个词的结果

词组查询

和查询词一致才返回结果


POST /user/_search
{
  "query": {
    "match_phrase": {
      "name": "小明"
    }
  }
}

组合查询或复合查询

POST /user/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "name.keyword": {
              "value": "大明"
            }
          }
        }
      ],
      "should": [
        {
          "range": {
            "age": {
              "gte": 10,
              "lte": 200
            }
          }
        }
      ]
    }
  }
}
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页