ES 根据ID查询文档

15,554 阅读1分钟

每个文档都有一个 _id 唯一标识,这个id可以在创建文档的时候手动传入或者由es自己生成。

_id 字段在做聚合、排序、脚本时功能受限,如果说上述操作需要用到 _id 字段,需要把 _id 的值在 doc_values 里也保存一份

创建文档

# Example
PUT {my_index}/_doc/1
{
    "text":"document with id 1"
}

PUT {my_index}/_doc
{
    "text":"document with auto generate"
}

根据id查询文档

  • 根据 get api 查询
  • 根据 ids query 查询
  • 根据 term , terms , match 查询

get api 查询

GET {my_index}/_doc/{myid}
GET books_index/_doc/1

ids query 查询

# query docs with id in (1,2,3)
GET {my_index}/_search
{
    "query":
    {
        "ids":
        {
            "values":[1,2,3]
        }
    }
}

term terms match 查询

# term
GET {my_index}/_search
{
  "query": {
      "term": {
        "_id": {
          "value": "1"
        }
      }    
    }
  }
}

# terms
GET {my_index}/_search
{
  "query": {
     "terms": {
       "_id": [
         "1","2"
       ]
     }
    }
  }
}

# match
GET {my_index}/_search
{
  "query": {
      "match": {
        "_id": 1
      }
    }
  }
}