ElasticSearch6.x学习笔记:29.JavaAPI之MatchAllQuery
程序员文章站
2022-04-21 20:48:39
Elasticsearch provides a full Java query dsl in a similar manner to the REST Query DSL. The fact...
Elasticsearch provides a full Java query dsl in a similar manner to the REST Query DSL. The factory for query builders is QueryBuilders. Once your query is ready, you can use the Search API.
Elasticsearch以类似于REST Query DSL的方式提供完整的Java查询dsl。 查询构建器的工厂是QueryBuilders。 一旦您的查询准备就绪,您可以使用搜索API。
package cn.hadron; import cn.hadron.es.ESUtil; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import java.util.Map; public class MatchAllQuery { public static void main(String[] args) { TransportClient client = ESUtil.getClient(); //构造查询对象 QueryBuilder query= QueryBuilders.matchAllQuery(); //搜索结果存入SearchResponse SearchResponse response=client.prepareSearch("my-index") .setQuery(query) //设置查询器 .setSize(3) //一次查询文档数 .get(); SearchHits hits=response.getHits(); for(SearchHit hit:hits){ System.out.println("source:"+hit.getSourceAsString()); System.out.println("index:"+hit.getIndex()); System.out.println("type:"+hit.getType()); System.out.println("id:"+hit.getId()); //遍历文档的每个字段 Map map=hit.getSourceAsMap(); for(String key:map.keySet()){ System.out.println(key+"="+map.get(key)); } System.out.println("--------------------"); } } }
执行结果
no modules loaded loaded plugin [org.elasticsearch.index.reindex.ReindexPlugin] loaded plugin [org.elasticsearch.join.ParentJoinPlugin] loaded plugin [org.elasticsearch.percolator.PercolatorPlugin] loaded plugin [org.elasticsearch.script.mustache.MustachePlugin] loaded plugin [org.elasticsearch.transport.Netty4Plugin] source:{ "name":"程裕强", "age":31, "gender":"男", "salary":20000, "dep":"bigdata" } index:my-index type:persion id:5 gender=男 name=程裕强 salary=20000 age=31 dep=bigdata -------------------- source:{ "name":"李四", "age":26, "gender":"女", "salary":15000, "dep":"bigdata" } index:my-index type:persion id:2 gender=女 name=李四 salary=15000 age=26 dep=bigdata -------------------- source:{ "name":"刘六", "age":27, "gender":"女", "salary":18000, "dep":"AI" } index:my-index type:persion id:4 gender=女 name=刘六 salary=18000 age=27 dep=AI -------------------- Process finished with exit code 0