Elasticsearch javaApi 查询

Elasticsearch javaApi 查询


elasticsearch javaApi调用,实现条件查询~当前版本为elasticsearch 2.3X,es版本5.5版本后api有区别

引入pom依赖

 		
            org.elasticsearch
            elasticsearch
            2.3.4
        

工具类上实例化es客户端

public class EsUtil {
    static Client client = null;

    static {
        //设置集群名字
        Settings settings = Settings.settingsBuilder()
                .put("cluster.name", "xxxxx")
                .put("client.transport.sniff", true)
                .build();
        try {
            //初始化连接客户端
            client = new TransportClient.Builder().settings(settings).build()
                    .addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress("192.168.xxx,xx", 9300)));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    }

查询
精确匹配所有

 SearchResponse response = client.prepareSearch("索引")
                .setTypes("type")
                .setQuery(QueryBuilders.matchAllQuery()) // 匹配所有
                // 指定返回字段和排除字段
                .setFetchSource(new String[]{"shop_id", "shop_name"}, null)
                  .setFrom(pageNum).setSize(pageSize)  // 分页
                 .addSort("add_time", SortOrder.DESC) // 排序
                .execute()
                .actionGet();

范围查询

 .setQuery(QueryBuilders.rangeQuery("add_time").gte(format).format("yyyy-MM-dd HH:mm:ss"))

模糊查询

QueryBuilders.matchPhraseQuery(key, queryMap.get(key))

聚合查询

	BoolQueryBuilder bqb = new BoolQueryBuilder();
	bqb.must(QueryBuilders.rangeQuery(key).gte(today).lt(format).format("yyyy-MM-dd HH:mm:ss"));
	bqb.must(QueryBuilders.matchPhraseQuery(key, queryMap.get(key)));

设置高亮

查询时:
  SearchRequestBuilder srb = client.prepareSearch("索引");
  srb.setTypes("type");
  srb.addHighlightedField("shop_name");
     srb.addHighlightedField("area");
     srb.addHighlightedField("wangwang");
     srb.addHighlightedField("category");
  srb.setExplain(true).setFrom(pageNo).setSize(pageSize).addSort("id", SortOrder.DESC).execute().actionGet();

结果处理:
  			Map result = hit.getHighlightFields();
            String shopName = "";
            
              HighlightField shopNameField = result.get("shop_name");
            if (shopNameField != null) {
                Text[] fragments = shopNameField.fragments();
                for (Text text : fragments) {
                    shopName += text;
                }
            }
            此时 shopName 即为高亮

你可能感兴趣的:(elasticsearch,elasticsearch,java)