elasticsearch 2.x工具类,复杂查询

零度    2018/02/21    总阅读量

高并发、锁   思考   面试   实践   Netty   Linux   Redis   MySQL   Nginx   Maven   Git   ElasticSearch   Spring  
import java.net.InetAddress;  
import java.util.ArrayList;  
import java.util.List;  
import java.util.Map;  
  
import org.elasticsearch.action.get.GetRequest;  
import org.elasticsearch.action.get.GetResponse;  
import org.elasticsearch.action.search.SearchRequestBuilder;  
import org.elasticsearch.action.search.SearchResponse;  
import org.elasticsearch.action.search.SearchType;  
import org.elasticsearch.client.Client;  
import org.elasticsearch.client.transport.TransportClient;  
import org.elasticsearch.common.settings.Settings;  
import org.elasticsearch.common.text.Text;  
import org.elasticsearch.common.transport.InetSocketTransportAddress;  
import org.elasticsearch.index.query.BoolQueryBuilder;  
import org.elasticsearch.index.query.QueryBuilders;  
import org.elasticsearch.index.query.QueryStringQueryBuilder;  
import org.elasticsearch.index.query.QueryStringQueryBuilder.Operator;  
import org.elasticsearch.search.SearchHit;  
import org.elasticsearch.search.SearchHits;  
import org.elasticsearch.search.highlight.HighlightField;  
import org.elasticsearch.search.sort.SortOrder;  
  
import com.alibaba.fastjson.JSON;  
import com.tts.util.DateFormatUtil;  
  
/** 
 * 类名称:  ESUtil    
 * 描述:  es工具类 
 * 
 */  
public class ESUtil {  
    private Client client;  
  
    {  
        Settings settings = Settings.settingsBuilder().build();  
        try {  
            client = TransportClient.builder().settings(settings).build()  
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("xxx.xxx.xxx.xxx"), 9300));  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
  
    /** 
     * 查询 
     */  
    public long query(String keyWord, String stDate, String enDate, String dataType, int currentPage, int rowNum,  
            List<Map<String, Object>> list) {  
  
        long num = 0;  
		QueryStringQueryBuilder queryBuilders = QueryBuilders.queryStringQuery(keyWord).defaultOperator(Operator.AND).field("full_name");
  
  
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();  
        boolQueryBuilder.must(queryBuilders);  
        boolQueryBuilder.filter(QueryBuilders.boolQuery().must(  
                QueryBuilders.rangeQuery("logdate").gte(stDate).lte(enDate).format("yyyy-MM-dd HH:mm:ss")));  
  
        SearchRequestBuilder searchRequestBuilder = client.prepareSearch("logstash-2").setTypes("biglog")  
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)  
                .setQuery(boolQueryBuilder);  
  
        searchRequestBuilder.addHighlightedField("*");  
  
        SearchResponse response = searchRequestBuilder.setHighlighterPreTags("<font color='red'>")  
				.setHighlighterPostTags("</font>").setHighlighterFragmentSize(10000000).setHighlighterRequireFieldMatch(false)
                .setFrom((currentPage - 1) * rowNum).setSize(rowNum).addSort("logdate", SortOrder.DESC)  
                .setExplain(true).get();  
  
        SearchHits hits = response.getHits();  
        num = hits.getTotalHits();  
        System.out.println("总量" + hits.getTotalHits());  
        SearchHit[] hitArray = hits.hits();  
        for (SearchHit hit : hitArray) {  
            Map<String, Object> map = hit.getSource();  
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();  
  
            // 打印高亮显示内容  
            for (Map.Entry<String, HighlightField> entry : highlightFields.entrySet()) {  
                StringBuilder sb = new StringBuilder();  
                Text[] text = entry.getValue().fragments();  
                for (Text str : text) {  
                    sb.append(str.string());  
                }  
  
                map.put(entry.getKey(), sb.toString());  
            }  
  
            list.add(map);  
        }  
  
        return num;  
    }  
  
    /** 
     * 根据id查询 
     */  
    public Map<String, Object> queryById(String id) {  
  
        GetResponse response = client.get(new GetRequest("logstash-2", "biglog", id)).actionGet();  
        if (!response.isSourceEmpty()) {  
            return response.getSource();  
        }  
        return null;  
    }  
  
    public static void main(String[] args) {  
        ESUtil es = new ESUtil();  
  
        /* 
         * Map<String, Object> map = es.queryById("yu6ZUeu31vUcAW6s6eh"); System.out.println(JSON.toJSONString(map)); 
         */  
  
        es.query("测试  看看", "2017-02-17 17:12:07", "2017-02-19 17:21:08",  
                null, 5, 10, new ArrayList<Map<String, Object>>());  
    }  
}  


扫描关注:匠心零度

(转载本站文章请注明作者和出处 匠心零度-jiangxinlingdu

Show Disqus Comments

腾讯云:新客户代金券
腾讯云:3年时长最低265元/年
阿里云:ECS云服务器2折起

目录