一. 创建Maven项目
1.1 导入pom.xml
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>5.4.2</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.4.2</version>
</dependency>
主版本需要与服务器版本一致
1.2 elasticsearch.yml
二 . 查询代码实例
2.1 代码
//指定Es集群 Settings settings = Settings.builder().put("cluster.name","my-elasticsearch").build(); //创建访问Es服务器的客户端 TransportClient client = new PreBuiltTransportClient(settings) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"), 9300)); //数据查询 GetResponse rs=client.prepareGet("lib","user","AW4ba3-CtOQsl6jnKxI_").get(); //得到查询出的数据 System.out.println(rs.getSourceAsString()); System.out.println("-----------"); //只取名称 System.out.println(rs.getSource().get("name")); client.close();
三 . 添加文档代码实例
3.1 代码
//指定Es集群 Settings settings = Settings.builder().put("cluster.name","my-elasticsearch").build(); //创建访问Es服务器的客户端 TransportClient client = new PreBuiltTransportClient(settings) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"), 9300)); //组建文档内容 XContentBuilder doc=XContentFactory.jsonBuilder() .startObject() .field("id",1) .field("title","java设计模式之装饰模式") .field("content","春天,我们去郊游,杏花吹了一头,这是多么惬意和美好,就像美好洒了一头一样。好巧不巧,在这里," + "碰到一个风流倜傥的男子,我真的好喜欢他。美丽的春日,碰到一见钟情的人,有比这更美好的事吗?") .field("postdate","2020-01-09") .field("url","http://192.168.95.4:5601/app/kibana#/dev_tools/console?_g=()") .endObject(); //添加文档 IndexResponse response=client.prepareIndex("lib", "blog","1") .setSource(doc).get(); //返回状态是否添加成功 System.out.println(response.status()); //关闭来连接 client.close();
四. 删除文档代码实例
4.1 .1代码部分
//指定Es集群 Settings settings = Settings.builder().put("cluster.name","my-elasticsearch").build(); //创建访问Es服务器的客户端 TransportClient client = new PreBuiltTransportClient(settings) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"), 9300)); //删除文档 DeleteResponse rs=client.prepareDelete("lib", "blog","1").get(); //返回状态是否删除成功 System.out.println(rs.status()); //关闭来连接 client.close();
4.2.1 存在即修改,不存就报错
//指定Es集群 Settings settings = Settings.builder().put("cluster.name","my-elasticsearch").build(); //创建访问Es服务器的客户端 TransportClient client = new PreBuiltTransportClient(settings) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"), 9300)); //修改文档 UpdateRequest rqs=new UpdateRequest(); rqs.index("lib") .type("blog") .id("1") .doc( XContentFactory.jsonBuilder().startObject() .field("title","java设计模式之单列设计模式").endObject() ); UpdateResponse rps=client.update(rqs).get(); //返回状态是否删除成功 System.out.println(rps.status()); //关闭来连接 client.close();
4.2.2 文档不存在就添加,存在就修改
//指定Es集群 Settings settings = Settings.builder().put("cluster.name","my-elasticsearch").build(); //创建访问Es服务器的客户端 TransportClient client = new PreBuiltTransportClient(settings) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"), 9300)); //修改文档,不存在就添加 IndexRequest inq=new IndexRequest("lib", "blog", "2") .source( XContentFactory.jsonBuilder() .startObject() .field("id",2) .field("title","工厂模式") .field("content","静态工厂,实例工") .field("postdate","2020-02-10") .field("url","http://192.168.95.4:5601/app/kibana#/dev_tools/console?_g=()") .endObject() ); //先修改,文档不存在执行后面的添加 UpdateRequest uq=new UpdateRequest("lib", "blog", "3") .doc( XContentFactory.jsonBuilder() .startObject() .field("title","设计模式") .endObject() ).upsert(inq); //执行操作 UpdateResponse rps=client.update(uq).get(); //返回状态是否删除成功 System.out.println(rps.status()); //关闭来连接 client.close();
五.java应用中实现批量操作(mget&bulk)
5.1.1 mget批量查询 ,java代码
//1.指定es集群
Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
//2.创建访问es服务器的客服端
TransportClient client=new PreBuiltTransportClient(setting)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));//配置查询信息
MultiGetResponse mget=client.prepareMultiGet()
.add("lib", "blog", "1")
.add("lib", "blog", "3").get();
//展示信息
for(MultiGetItemResponse ms:mget) {
GetResponse grp=ms.getResponse();
if(grp.isExists()&&grp!=null) {
System.out.println(grp.getSourceAsString());
System.err.println("___");
//System.out.println(grp.getSource().get("content"));//指定输出属性
}
}
5.2.1 bulk批量添加,java代码
//1.指定es集群
Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
//2.创建访问es服务器的客服端
TransportClient client=new PreBuiltTransportClient(setting)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));
BulkRequestBuilder bulkbuild=client.prepareBulk();
//批量添加
bulkbuild.add(client.prepareIndex("lib1","books","1")
.setSource(
XContentFactory.jsonBuilder()
.startObject()
.field("title","python")
.field("price", 99)
.endObject()
)
);
bulkbuild.add(client.prepareIndex("lib1","books","2")
.setSource(
XContentFactory.jsonBuilder()
.startObject()
.field("title","vr")
.field("price", 39)
.endObject()
)
);
//执行操作
BulkResponse rps=bulkbuild.get();
//执行结果
System.out.println(rps.status());
if(rps.hasFailures()) {
System.out.println("失败了!");
}
5.3.1 bulk查询符合条件的属性,删除文档,java代码
//1.指定es集群
Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
//2.创建访问es服务器的客服端
TransportClient client=new PreBuiltTransportClient(setting)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));
BulkRequestBuilder bulkbuild=client.prepareBulk();
BulkByScrollResponse rsp=DeleteByQueryAction.INSTANCE
.newRequestBuilder(client)
.filter(QueryBuilders.matchQuery("title", "设计"))
//指定索引
.source("lib").get();
//返回结果,返回影响行数
long result=rsp.getDeleted();
System.out.println(result);
5.4.1 全部查询,java代码
//1.指定es集群 Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build(); //2.创建访问es服务器的客服端 TransportClient client=new PreBuiltTransportClient(setting) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300)); //查询所有 MatchAllQueryBuilder qd=QueryBuilders.matchAllQuery(); SearchResponse sr=client.prepareSearch("lib*") .setQuery(qd) .setSize(5).get(); //查出所有文档 SearchHits hits=sr.getHits(); //迭代器打印结果 Iterator<SearchHit> it=hits.iterator(); while(it.hasNext()) { Map<String,Object> map=it.next().getSourceAsMap(); for(String key:map.keySet()) { System.out.println(key+":"+map.get(key)); } System.out.println("--------------"); } client.close();
六. java中实现match与multimatch查询
6.1 .1 matc指定条件查询,java代码
//1.指定es集群 Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build(); //2.创建访问es服务器的客服端 TransportClient client=new PreBuiltTransportClient(setting) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300)); //查询content属性中带有"工厂"的文档,模糊查询,用的ik分词器 MatchQueryBuilder builder=QueryBuilders.matchQuery("content", "工厂"); SearchResponse sr=client.prepareSearch("lib*") .setQuery(builder) .setSize(5).get(); //查出所有文档 SearchHits hits=sr.getHits(); //迭代器打印结果 Iterator<SearchHit> it=hits.iterator(); while(it.hasNext()) { Map<String,Object> map=it.next().getSourceAsMap(); for(String key:map.keySet()) { System.out.println(key+":"+map.get(key)); } System.out.println("--------------"); } client.close();
6.2.1 multiMatch多条件查询,java代码
@Test public void multiMatchByElasticsearch() throws IOException { //1.指定es集群 Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build(); //2.创建访问es服务器的客服端 TransportClient client=new PreBuiltTransportClient(setting) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300)); //查询content属性title中带有"一见钟情"的文档,模糊查询,用的ik分词器 MultiMatchQueryBuilder builder=QueryBuilders.multiMatchQuery("一见钟情", "content","title"); //从全部以lib开始的索引下找,显示5条 SearchResponse sr=client.prepareSearch("lib*") .setQuery(builder) .setSize(5).get(); //查出所有文档 SearchHits hits=sr.getHits(); //迭代器打印结果 Iterator<SearchHit> it=hits.iterator(); while(it.hasNext()) { Map<String,Object> map=it.next().getSourceAsMap(); for(String key:map.keySet()) { System.out.println(key+":"+map.get(key)); } System.out.println("--------------"); } client.close(); }
七.term和terms查询
7.1.1 term条件查询,java代码
//1.指定es集群 Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build(); //2.创建访问es服务器的客服端 TransportClient client=new PreBuiltTransportClient(setting) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300)); //查询content属性title中带有"静态"的文档,模糊查询,用的ik分词器 TermQueryBuilder builder=QueryBuilders.termQuery("content","静态"); //从全部以lib开始的索引下找,显示5条 SearchResponse sr=client.prepareSearch("lib*") .setQuery(builder) .setSize(5).get(); //查出所有文档 SearchHits hits=sr.getHits(); //迭代器打印结果 Iterator<SearchHit> it=hits.iterator(); while(it.hasNext()) { Map<String,Object> map=it.next().getSourceAsMap(); for(String key:map.keySet()) { System.out.println(key+":"+map.get(key)); } System.out.println("--------------"); } client.close();
7.2.1 terms多条件查询(指定一个属性配配多个值)
//1.指定es集群 Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build(); //2.创建访问es服务器的客服端 TransportClient client=new PreBuiltTransportClient(setting) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300)); //查询content属性中带有"工厂"或者"春天"的所有文档,一个属性匹配多个值,模糊查询,用的ik分词器 TermsQueryBuilder builder=QueryBuilders.termsQuery("content","工厂","春天"); //从全部以lib开始的索引下找,显示5条 SearchResponse sr=client.prepareSearch("lib*") .setQuery(builder) .setSize(5).get(); //查出所有文档 SearchHits hits=sr.getHits(); //迭代器打印结果 Iterator<SearchHit> it=hits.iterator(); while(it.hasNext()) { Map<String,Object> map=it.next().getSourceAsMap(); for(String key:map.keySet()) { System.out.println(key+":"+map.get(key)); } System.out.println("--------------"); } client.close();
八 . java中实现range,prefix,wildcard,fuzzy,type,ids查询
8.1.1 range时间范围查询,java代码
//1.指定es集群 Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build(); //2.创建访问es服务器的客服端 TransportClient client=new PreBuiltTransportClient(setting) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300)); //range查询,查询postdate时间范围在"2018-01-01~2030-01-01"之间的文档记录 RangeQueryBuilder builder=QueryBuilders.rangeQuery("postdate").from("2018-01-01").to("2030-01-01").format("yyyy-MM-dd"); //从全部以lib开始的索引下找,查询所有 SearchResponse sr=client.prepareSearch("lib*") .setQuery(builder).get(); //查出所有文档 SearchHits hits=sr.getHits(); //迭代器打印结果 Iterator<SearchHit> it=hits.iterator(); while(it.hasNext()) { Map<String,Object> map=it.next().getSourceAsMap(); for(String key:map.keySet()) { System.out.println(key+":"+map.get(key)); } System.out.println("--------------"); } client.close();
8.2.1 prefix(前缀)查询,java代码
//1.指定es集群 Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build(); //2.创建访问es服务器的客服端 TransportClient client=new PreBuiltTransportClient(setting) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300)); //prefix查询,查询url内容以http开头的 PrefixQueryBuilder builder=QueryBuilders.prefixQuery("url","http"); //从全部以lib开始的索引下找,查询所有 SearchResponse sr=client.prepareSearch("lib*") .setQuery(builder).get(); //查出所有文档 SearchHits hits=sr.getHits(); //迭代器打印结果 Iterator<SearchHit> it=hits.iterator(); while(it.hasNext()) { Map<String,Object> map=it.next().getSourceAsMap(); for(String key:map.keySet()) { System.out.println(key+":"+map.get(key)); } System.out.println("--------------"); } client.close();
8.3.1 wildcard(通配符)查询
//1.指定es集群 Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build(); //2.创建访问es服务器的客服端 TransportClient client=new PreBuiltTransportClient(setting) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300)); //wildcard(通配符)查询,查询content内容有“春日”的文档 WildcardQueryBuilder builder=QueryBuilders.wildcardQuery("content","*春日*"); //从全部以lib开始的索引下找,查询所有 SearchResponse sr=client.prepareSearch("lib*") .setQuery(builder).get(); //查出所有文档 SearchHits hits=sr.getHits(); //迭代器打印结果 Iterator<SearchHit> it=hits.iterator(); while(it.hasNext()) { Map<String,Object> map=it.next().getSourceAsMap(); for(String key:map.keySet()) { System.out.println(key+":"+map.get(key)); } System.out.println("--------------"); } client.close();
8.4.1 Fuzzy(模糊)查询,java代码
//1.指定es集群 Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build(); //2.创建访问es服务器的客服端 TransportClient client=new PreBuiltTransportClient(setting) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300)); //fuzzy(模糊)查询,查询content内容有“好巧”的文档 FuzzyQueryBuilder builder=QueryBuilders.fuzzyQuery("content","更美好"); //从全部以lib开始的索引下找 SearchResponse sr=client.prepareSearch("lib*") .setQuery(builder).get(); //查出所有文档 SearchHits hits=sr.getHits(); //迭代器打印结果 Iterator<SearchHit> it=hits.iterator(); while(it.hasNext()) { Map<String,Object> map=it.next().getSourceAsMap(); for(String key:map.keySet()) { System.out.println(key+":"+map.get(key)); } System.out.println("--------------"); } client.close();
8.5.1 Type(类型)查询,java代码
//1.指定es集群 Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build(); //2.创建访问es服务器的客服端 TransportClient client=new PreBuiltTransportClient(setting) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300)); //type(类型)查询,查询类型为“blog”的文档 TypeQueryBuilder builder=QueryBuilders.typeQuery("books"); //从全部以lib开始的索引下找 SearchResponse sr=client.prepareSearch("lib*") .setQuery(builder).get(); //查出所有文档 SearchHits hits=sr.getHits(); //迭代器打印结果 Iterator<SearchHit> it=hits.iterator(); while(it.hasNext()) { Map<String,Object> map=it.next().getSourceAsMap(); for(String key:map.keySet()) { System.out.println(key+":"+map.get(key)); } System.out.println("--------------"); } client.close();
8.6.1 Ids查询,java代码
//1.指定es集群 Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build(); //2.创建访问es服务器的客服端 TransportClient client=new PreBuiltTransportClient(setting) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300)); //ids查询,根据指定的id查询 IdsQueryBuilder builder=QueryBuilders.idsQuery().addIds("1","2"); //从全部以lib开始的索引下找 SearchResponse sr=client.prepareSearch("lib") .setQuery(builder).get(); //查出所有文档 SearchHits hits=sr.getHits(); //迭代器打印结果 Iterator<SearchHit> it=hits.iterator(); while(it.hasNext()) { Map<String,Object> map=it.next().getSourceAsMap(); for(String key:map.keySet()) { System.out.println(key+":"+map.get(key)); } System.out.println("--------------"); } client.close();
九 .聚合查询
9.1.1 max最大值查询,java代码
//1.指定es集群 Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build(); //2.创建访问es服务器的客服端 TransportClient client=new PreBuiltTransportClient(setting) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300)); //Max查询,price(价格)最大值查询 AggregationBuilder agg=AggregationBuilders.max("aggMax").field("price"); //从全部以lib开始的索引下找 SearchResponse rsp=client.prepareSearch("lib*").addAggregation(agg).get(); //取到最大值 Max max=rsp.getAggregations().get("aggMax"); //输出最大值 System.out.println(max.getName()+":"+max.getValue()); client.close();
9.2.1 min最小值查询,java代码
//1.指定es集群 Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build(); //2.创建访问es服务器的客服端 TransportClient client=new PreBuiltTransportClient(setting) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300)); //min查询,price(价格)最小值查询 AggregationBuilder agg=AggregationBuilders.min("aggMin").field("price"); //从全部以lib开始的索引下找 SearchResponse rsp=client.prepareSearch("lib*").addAggregation(agg).get(); //取到最小值 Min min=rsp.getAggregations().get("aggMin"); //输出最小值 System.out.println(min.getName()+":"+min.getValue()); client.close();
9.3.1 avg平均值查询,java代码
//1.指定es集群 Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build(); //2.创建访问es服务器的客服端 TransportClient client=new PreBuiltTransportClient(setting) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300)); //平均值查询,price(价格)平均值查询 AggregationBuilder agg=AggregationBuilders.avg("aggAvg").field("price"); //从全部以lib开始的索引下找 SearchResponse rsp=client.prepareSearch("lib*").addAggregation(agg).get(); //取到平均值 Avg avg=rsp.getAggregations().get("aggAvg"); //输出平均值 System.out.println(avg.getName()+":"+avg.getValue()); client.close();
9.4.1 Sum总和值查询,java代码
//1.指定es集群 Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build(); //2.创建访问es服务器的客服端 TransportClient client=new PreBuiltTransportClient(setting) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300)); //求总和值,price(价格)求总和值查询 AggregationBuilder agg=AggregationBuilders.sum("aggSum").field("price"); //从全部以lib开始的索引下找 SearchResponse rsp=client.prepareSearch("lib*").addAggregation(agg).get(); //取到总的价格 Sum sum=rsp.getAggregations().get("aggSum"); //输出求总和值 System.out.println(sum.getName()+":"+sum.getValue()); client.close();
9.5.1 cardinality查询,java代码
//1.指定es集群 Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build(); //2.创建访问es服务器的客服端 TransportClient client=new PreBuiltTransportClient(setting) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300)); //求基数值 AggregationBuilder agg=AggregationBuilders.cardinality("aggcardinality").field("price"); //从全部以lib开始的索引下找 SearchResponse rsp=client.prepareSearch("lib*").addAggregation(agg).get(); //取到有多少个基数值 Cardinality aggcardinality=rsp.getAggregations().get("aggcardinality"); //输出基数值 System.out.println(aggcardinality.getName()+":"+aggcardinality.getValue()); client.close();
十.其他查询
10.1.1 query String 条件查询,指定字段,java代码
//1.指定es集群 Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build(); //2.创建访问es服务器的客服端 TransportClient client=new PreBuiltTransportClient(setting) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300)); //全文查询,查询"python"这本书 CommonTermsQueryBuilder builder=QueryBuilders.commonTermsQuery("title", "python"); //从全部以lib开始的索引下找 SearchResponse rsp=client.prepareSearch("lib*").setQuery(builder).get(); //取到SearchHits对象 SearchHits hits=rsp.getHits(); for(SearchHit hit:hits) { System.out.println(hit.getSourceAsString()); } client.close();
10.2.1 query String 全文查询,不指定字段,两边都需要满足,java代码
//1.指定es集群 Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build(); //2.创建访问es服务器的客服端 TransportClient client=new PreBuiltTransportClient(setting) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300)); //全文查询,查询有"工厂"但不包含有"更美好"字段的这个文档 QueryStringQueryBuilder builder=QueryBuilders.queryStringQuery("+工厂 -更美好"); //从全部以lib开始的索引下找 SearchResponse rsp=client.prepareSearch("lib").setQuery(builder).get(); //取到SearchHits对象 SearchHits hits=rsp.getHits(); for(SearchHit hit:hits) { System.out.println(hit.getSourceAsString()); } client.close();
10.3.1 query String 全文查询,满足其中一个,不指定字段,java代码
//1.指定es集群 Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build(); //2.创建访问es服务器的客服端 TransportClient client=new PreBuiltTransportClient(setting) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300)); //全文查询,查询有"工厂"或者不包含有"更美好"字段的这个文档 SimpleQueryStringBuilder builder=QueryBuilders.simpleQueryStringQuery("+工厂 -更美好"); //从全部以lib开始的索引下找 SearchResponse rsp=client.prepareSearch("lib").setQuery(builder).get(); //取到SearchHits对象 SearchHits hits=rsp.getHits(); //迭代器打印结果 Iterator<SearchHit> it=hits.iterator(); while(it.hasNext()) { Map<String,Object> map=it.next().getSourceAsMap(); for(String key:map.keySet()) { System.out.println(key+":"+map.get(key)); } System.out.println("--------------"); } client.close();
10.4.1 组合查询,java代码
//1.指定es集群 Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build(); //2.创建访问es服务器的客服端 TransportClient client=new PreBuiltTransportClient(setting) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300)); //组合查询 BoolQueryBuilder builder=QueryBuilders.boolQuery() .must(QueryBuilders.matchQuery("content","工厂"))//必须包含 .mustNot(QueryBuilders.matchQuery("content", "全部"))//不包含 .should(QueryBuilders.matchQuery("title", "语法"))//或者包含 //时间过滤(大于2020-03-01) .filter(QueryBuilders.rangeQuery("postdate").gte("2020-03-01").format("yyyy-MM-dd")); //从全部以lib开始的索引下找 SearchResponse rsp=client.prepareSearch("lib").setQuery(builder).get(); //取到SearchHits对象 SearchHits hits=rsp.getHits(); //迭代器打印结果 Iterator<SearchHit> it=hits.iterator(); while(it.hasNext()) { Map<String,Object> map=it.next().getSourceAsMap(); for(String key:map.keySet()) { System.out.println(key+":"+map.get(key)); } System.out.println("--------------"); } client.close();
10.5.1 constantScoreQuery查询,java代码
//1.指定es集群 Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build(); //2.创建访问es服务器的客服端 TransportClient client=new PreBuiltTransportClient(setting) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300)); //组合查询,查title中包含有“正则”的文档,与termQuery()的作用类似 ConstantScoreQueryBuilder builder=QueryBuilders.constantScoreQuery(QueryBuilders.termQuery("title","正则")); //从全部以lib开始的索引下找 SearchResponse rsp=client.prepareSearch("lib").setQuery(builder).get(); //取到SearchHits对象 SearchHits hits=rsp.getHits(); //迭代器打印结果 Iterator<SearchHit> it=hits.iterator(); while(it.hasNext()) { Map<String,Object> map=it.next().getSourceAsMap(); for(String key:map.keySet()) { System.out.println(key+":"+map.get(key)); } System.out.println("--------------"); } client.close();
十一.java应用中实现桶聚合
11.1 分组聚合java代码
/** * 桶聚合 * @throws IOException */ @Test public void Query2Elasticsearch() throws IOException { //1.指定es集群 Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build(); //2.创建访问es服务器的客服端 TransportClient client=new PreBuiltTransportClient(setting) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300)); //按标题分组显示 AggregationBuilder agg=AggregationBuilders.terms("terms").field("price"); //从全部以lib开始的索引下找 SearchResponse rsp=client.prepareSearch("lib1").addAggregation(agg).execute().actionGet(); //取到分组数据 Terms terms=rsp.getAggregations().get("terms"); for(Terms.Bucket te:terms.getBuckets()) { System.out.println(te.getKey()+":"+te.getDocCount()); } } }
11.2 filter聚合(分组过滤)
//1.指定es集群 Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build(); //2.创建访问es服务器的客服端 TransportClient client=new PreBuiltTransportClient(setting) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300)); ///需要查找price为6666的分组 TermQueryBuilder query=QueryBuilders.termQuery("price","6666"); //按标题分组显示 AggregationBuilder agg=AggregationBuilders.filter("filter",query); //从索引lib1下找 SearchResponse rsp=client.prepareSearch("lib1").addAggregation(agg).execute().actionGet(); //取到过滤后数据条数 Filter filter=rsp.getAggregations().get("filter"); System.out.println(filter.getDocCount());
11.3 filters聚合(多个过滤条件)
//1.指定es集群 Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build(); //2.创建访问es服务器的客服端 TransportClient client=new PreBuiltTransportClient(setting) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300)); //按标题分组显示 AggregationBuilder agg=AggregationBuilders.filters("filters", new FiltersAggregator.KeyedFilter("py", QueryBuilders.termsQuery("title","python")), new FiltersAggregator.KeyedFilter("vr", QueryBuilders.termsQuery("title","vr"))); //从索引lib1下找 SearchResponse rsp=client.prepareSearch("lib1").addAggregation(agg).execute().actionGet(); //取到过滤后数据条数 Filters filters=rsp.getAggregations().get("filters"); for(Filters.Bucket filter:filters.getBuckets()) { System.out.println(filter.getKey()+":"+filter.getDocCount()); }
11.4 range聚合
//1.指定es集群
Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
//2.创建访问es服务器的客服端
TransportClient client=new PreBuiltTransportClient(setting)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));
//按标题分组显示
AggregationBuilder agg=AggregationBuilders.range("range")
.field("price")
.addUnboundedTo(60) //小于60以下
.addRange(1,7000) //1-7000之间的
.addUnboundedFrom(50);//大于50以上的
//从索引lib1下找
SearchResponse rsp=client.prepareSearch("lib1").addAggregation(agg).execute().actionGet();
//取到过滤后数据条数
Range rang=rsp.getAggregations().get("range");
for(Range.Bucket r:rang.getBuckets()) {
System.out.println(r.getKey()+":"+r.getDocCount());
}
11.5 missing(统计属性为null的条数,如下其实“prices”这个属性是不存在的)
//1.指定es集群 Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build(); //2.创建访问es服务器的客服端 TransportClient client=new PreBuiltTransportClient(setting) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300)); //按标题分组显示 AggregationBuilder agg=AggregationBuilders.missing("missing").field("prices"); //从索引lib1下找 SearchResponse rsp=client.prepareSearch("lib1").addAggregation(agg).execute().actionGet(); //取到过滤后数据条数 Missing miss=rsp.getAggregations().get("missing"); System.out.println(miss.getDocCount());