1、CommonTersQuery: 指定字段进行模糊查询

//commonTermsQuery
@Test
public void test35() throws UnknownHostException{
//1、指定es集群 cluster.name 是固定的key值,my-application是ES集群的名称
Settings settings = Settings.builder().put("cluster.name", "my-application").build();
//2.创建访问ES服务器的客户端
TransportClient client = new PreBuiltTransportClient(settings)
.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.1.94"), 9300));
QueryBuilder builder = QueryBuilders.commonTermsQuery("name","zhaoliu");
SearchResponse response = client.prepareSearch("lib3").setQuery(builder).get();
SearchHits hits = response.getHits();
for(SearchHit hit:hits) {
System.out.println(hit.getSourceAsString());
//将获取的值转换成map的形式
Map<String, Object> map = hit.getSourceAsMap();
for(String key:map.keySet()) {
System.out.println(key +" key对应的值为:" +map.get(key));
}
}
}

2、queryStringQuery:

  说明:根据值去每个字段进行模糊查询 +代表必须含有  -代表不能含有

//queryStringQuery  根据值去每个字段进行模糊查询 +代表必须含有  -代表不能含有
@Test
public void test36() throws UnknownHostException{
//1、指定es集群 cluster.name 是固定的key值,my-application是ES集群的名称
Settings settings = Settings.builder().put("cluster.name", "my-application").build();
//2.创建访问ES服务器的客户端
TransportClient client = new PreBuiltTransportClient(settings)
.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.1.94"), 9300));
//查询文档中含必须含有changge,不含有hejiu的文档(会每个字段去查询)+代表必须含有 -代表不能含有
QueryBuilder builder = QueryBuilders.queryStringQuery("+changge -hejiu");
SearchResponse response = client.prepareSearch("lib3").setQuery(builder).get();
SearchHits hits = response.getHits();
for(SearchHit hit:hits) {
System.out.println(hit.getSourceAsString());
//将获取的值转换成map的形式
Map<String, Object> map = hit.getSourceAsMap();
for(String key:map.keySet()) {
System.out.println(key +" key对应的值为:" +map.get(key));
}
}
}

3、simpleQueryStringQuery

  说明:根据值去每个字段进行模糊查询 只要有一个符合就会返回该文章

//simpleQueryStringQuery  根据值去每个字段进行模糊查询 只要有一个符合就会返回该文章
@Test
public void test37() throws UnknownHostException{
//1、指定es集群 cluster.name 是固定的key值,my-application是ES集群的名称
Settings settings = Settings.builder().put("cluster.name", "my-application").build();
//2.创建访问ES服务器的客户端
TransportClient client = new PreBuiltTransportClient(settings)
.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.1.94"), 9300));
//只要所有字段中,含有changge或hejiui的都返回
QueryBuilder builder = QueryBuilders.simpleQueryStringQuery("changge hejiu");
SearchResponse response = client.prepareSearch("lib3").setQuery(builder).get();
SearchHits hits = response.getHits();
for(SearchHit hit:hits) {
System.out.println(hit.getSourceAsString());
//将获取的值转换成map的形式
Map<String, Object> map = hit.getSourceAsMap();
for(String key:map.keySet()) {
System.out.println(key +" key对应的值为:" +map.get(key));
}
}
}

下一篇博客本人将书写java操作elasticsearch实现组合桶聚合。对后期博客感兴趣的朋友可以关注交流,转发请说明出处,本人的博客地址为:https://www.cnblogs.com/chenyuanbo/

技术在于交流!

04-25 01:28