参考: Elasticsearch Reference [7.10] » Query DSL » Term-level queries » IDs
一、ID 查询
ES每一行数据,即文档都会有一个id,如果指定某一列field值作为id,则该列field必须为唯一键,类似于MySQL的UK;不过不指定,ES会自动生成,常常为了更好的定位数据,会指定一列满足UK的field作为文档的id,接下来我们说一下根据id查询。
类似MySQL的 where id=?
1.1、命令行
GET /sms-logs-index/_doc/1
1.2、java 代码
@Test
public void idQuery() throws IOException {
GetRequest request = new GetRequest(index);
GetResponse resp = client.get(request.id("1"), RequestOptions.DEFAULT);
System.out.println(resp);
}
二、IDs查询
根据多个id查询,类似MySQL中的where id in(id1,id2,id3)
2.1、命令行
POST /sms-logs-index/_search?pretty
{
"query": {
"ids": {
"values": [1,2,3]
}
}
}
2.2、java 代码
@Test
public void idsQuery() throws IOException {
//1。创建request对象,查询用的对象一般都是SearchRequest对象
SearchRequest mySearchRequest = new SearchRequest(index);
//2,指定查询条件,依赖查询条件的对象SearchSourceBuilder的对象
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.from(0).size(10).query(QueryBuilders.idsQuery().addIds("1", "2", "3"));
mySearchRequest.source(builder);
//3. 执行查询
SearchResponse search = client.search(mySearchRequest, RequestOptions.DEFAULT);
//4. 获取到_source中的数据,并展示
//注意RESTFUL风格上是两个hits,所以这里要两次getHits()
for (SearchHit hit : search.getHits().getHits()) {
Map<String, Object> result = hit.getSourceAsMap();
System.out.println(result);
}
}