Elasticsearch Query DSL使用记录

官网Query DSL

索引

# 创建索引
PUT test-data
# 删除索引
DELETE test-data
# 删除所有索引
DELETE *
# 测试索引是否存在
HEAD test-data
# 查看所有索引 `?v`为显示详细信息
GET _cat/indices?v

数据

# 添加数据 索引不存在会自动创建
POST test-data/_doc
{
  "name": "test"
}

# 添加数据并指定 id 为 1
POST test-data/_doc/1
{
  "name": "李磊"
}

# 根据id删除数据
DELETE test-data/_doc/1

# 根据条件删除索引数据
POST test-data/_delete_by_query
{
  "query": {
    "match_all": {}
  }
}

# 查询全部数据
GET test-data/_search

# 分词查询
# operator 默认为 or
GET test-data/_search
{
  "query": {
    "match": {
      "name":{
        "query": "Frank Alex",
        "operator": "and"
      }
    }
  }
}

# 精确查询 字符串类型字段 ES会生成 `字符名称.keyword` 字段用于精确搜索
GET test-data/_search
{
  "query": {
    "term": {
      "name.keyword": "李磊"
    }
  }
}

# 分词多字段查询
GET test-data/_search
{
  "query": {
    "multi_match": {
      "query": "test",
      "fields": [
        "account",
        "name"
      ]
    }
  }
}

# 分页查询 from 默认为 0
GET test-data/_search
{
  "from": 0,
  "size": 10
}

# 模糊查询 wildcard
# https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-wildcard-query.html
GET test-data/_search
{
  "query": {
    "wildcard": {
      "name": "name*"
    }
  }
}

# 模糊查询 fuzzy
# fuzziness 模糊字符最大个数 默认值为AUTO
# 如为2 目标值 abcd 可被 aaad abbd 检索到
# https://www.elastic.co/guide/en/elasticsearch/guide/current/fuzzy-query.html
GET test-data/_search
{
  "query": {
    "fuzzy": {
      "name": {
        "value": "test",
        "fuzziness": 1
      }
    }
  }
}

# 范围查询 大于等于18 小于20
GET test-data/_search
{
  "query": {
    "range": {
      "age": {
        "gte": 18,
        "lt": 20
      }
    }
  }
}

# 排序
GET test-data/_search
{
  "query": {
    "match_all": {}
  },
  "sort": [
    {
      "age": {
        "order": "asc"
      }
    }
  ]
}

# 排除字段显示字段
# 指定显示字段 includes
# 排除显示字段 excludes
# 两者共存时 includes生效
# includes可以缩写为 "_source": ["name", ...]
GET test-data/_search
{
  "query": {
    "match_all": {}
  },
  "_source": {
    "includes": ["name", "age"],
    "excludes": ["create_time", "update_time"]
  }
}

# 多个条件使用 bool -> must 结构
GET test-data/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "name": "name"
          }
        },
        {
          "match": {
            "age": 20
          }
        }
      ]
    }
  }
}

  • text 写入值时 对值进行分词 插入到倒排索引
  • keyword 写入值时 直接将值 插入到倒排索引
  • match 分词查询 对查询值分词后 匹配倒排索引
  • term 精确查询 直接对查询值 匹配倒排索引
  • 写入值 a b
查询类型 写入类型 结果
term text 匹配 a b
term keyword 匹配 a b
match text 匹配 a b a b
match keyword 匹配 a b
上一篇:力扣-递归/回溯-字母大小写全排列


下一篇:前端与 DSL