Java Code Examples for org.elasticsearch.action.search.SearchRequestBuilder#setExplain()

The following examples show how to use org.elasticsearch.action.search.SearchRequestBuilder#setExplain() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ElasticsearchTransportFactory.java    From database-transform-tool with Apache License 2.0 7 votes vote down vote up
public String selectMatchAll(String indexs,String types,String field,String value){
	try {
		if(client==null){
			init();
		}
		SearchRequestBuilder request = client.prepareSearch(indexs.split(",")).setTypes(types.split(","));
		request.setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
		request.setQuery(QueryBuilders.matchQuery(field, value));
		request.highlighter(new HighlightBuilder().field(field));
		request.addAggregation(AggregationBuilders.terms("data").field(field+".keyword"));
		request.setExplain(false);
		SearchResponse response = request.get();
		return response.toString();
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return null;
}
 
Example 2
Source File: ElasticsearchExtendTransportFactory.java    From database-transform-tool with Apache License 2.0 7 votes vote down vote up
public String selectTermAll(String indexs,String types,String field,String value){
	try {
		if(client==null){
			init();
		}
		SearchRequestBuilder request = client.prepareSearch(indexs.split(",")).setTypes(types.split(","));
		request.setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
		request.setQuery(QueryBuilders.termQuery(field, value));
		request.highlighter(new HighlightBuilder().field(field));
		request.addAggregation(AggregationBuilders.terms("data").field(field+".keyword"));
		request.setExplain(false);
		SearchResponse response = request.get();
		return response.toString();
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return null;
}
 
Example 3
Source File: ElasticsearchTransportFactory.java    From database-transform-tool with Apache License 2.0 6 votes vote down vote up
public String selectAll(String indexs,String types,String condition){
	try {
		if(client==null){
			init();
		}
		SearchRequestBuilder request = client.prepareSearch(indexs.split(",")).setTypes(types.split(","));
		request.setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
		request.setQuery(QueryBuilders.queryStringQuery(condition));
		request.setExplain(false);
		SearchResponse response = request.get();
		return response.toString();
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return null;
}
 
Example 4
Source File: EsAbstractConditionBean.java    From fess with Apache License 2.0 5 votes vote down vote up
public void build(SearchRequestBuilder builder) {
    if (explain != null) {
        builder.setExplain(explain);
    }
    if (minScore != null) {
        builder.setMinScore(minScore);
    }
    if (preference != null) {
        builder.setPreference(preference);
    }
    if (routing != null) {
        builder.setRouting(routing);
    }
    if (searchType != null) {
        builder.setSearchType(searchType);
    }
    if (timeoutInMillis != -1) {
        builder.setTimeout(new TimeValue(timeoutInMillis));
    }
    if (version != null) {
        builder.setVersion(version);
    }
    if (seqNoAndPrimaryTerm != null) {
        builder.seqNoAndPrimaryTerm(seqNoAndPrimaryTerm);
    }
    if (terminateAfter > 0) {
        builder.setTerminateAfter(terminateAfter);
    }
}
 
Example 5
Source File: EsAbstractConditionBean.java    From fess with Apache License 2.0 5 votes vote down vote up
public void build(SearchRequestBuilder builder) {
    if (explain != null) {
        builder.setExplain(explain);
    }
    if (minScore != null) {
        builder.setMinScore(minScore);
    }
    if (preference != null) {
        builder.setPreference(preference);
    }
    if (routing != null) {
        builder.setRouting(routing);
    }
    if (searchType != null) {
        builder.setSearchType(searchType);
    }
    if (timeoutInMillis != -1) {
        builder.setTimeout(new TimeValue(timeoutInMillis));
    }
    if (version != null) {
        builder.setVersion(version);
    }
    if (seqNoAndPrimaryTerm != null) {
        builder.seqNoAndPrimaryTerm(seqNoAndPrimaryTerm);
    }
    if (terminateAfter > 0) {
        builder.setTerminateAfter(terminateAfter);
    }
}
 
Example 6
Source File: EsAbstractConditionBean.java    From fess with Apache License 2.0 5 votes vote down vote up
public void build(SearchRequestBuilder builder) {
    if (explain != null) {
        builder.setExplain(explain);
    }
    if (minScore != null) {
        builder.setMinScore(minScore);
    }
    if (preference != null) {
        builder.setPreference(preference);
    }
    if (routing != null) {
        builder.setRouting(routing);
    }
    if (searchType != null) {
        builder.setSearchType(searchType);
    }
    if (timeoutInMillis != -1) {
        builder.setTimeout(new TimeValue(timeoutInMillis));
    }
    if (version != null) {
        builder.setVersion(version);
    }
    if (seqNoAndPrimaryTerm != null) {
        builder.seqNoAndPrimaryTerm(seqNoAndPrimaryTerm);
    }
    if (terminateAfter > 0) {
        builder.setTerminateAfter(terminateAfter);
    }
}
 
Example 7
Source File: ESSearch.java    From common-project with Apache License 2.0 4 votes vote down vote up
public List<Map<String, Object>> execute() throws Exception {
    if (StringUtils.isEmpty(indexName)&& ArrayUtils.isEmpty(types)){
        throw new Exception("indexName or types is null");
    }
    SearchRequestBuilder searchRequestBuilder = transportClient.prepareSearch(this.indexName).setTypes(this.types);
    if (page>0&&pageSize>0){
        searchRequestBuilder.setFrom(this.page).setSize(this.pageSize);
    }

    if (!ArrayUtils.isEmpty(showField)){
        searchRequestBuilder.setFetchSource(showField,null);
    }
    if (size>0){
        searchRequestBuilder.setSize(size);
    }
    searchRequestBuilder.setFetchSource(true);
    //按字段排序
    if (!StringUtils.isEmpty(sortField)){
        String[] split = sortField.split(" ");
        if (split[1].equalsIgnoreCase("asc")){
            searchRequestBuilder.addSort(split[0], SortOrder.ASC);
        }
        if (split[1].equalsIgnoreCase("desc")){
            searchRequestBuilder.addSort(split[0], SortOrder.DESC);
        }

    }
    BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
    if (bean!=null){
        Map<String, Object> fieldNameAndVauleMapping = ClassUtil.getNotNullFieldNameAndVauleMapping(this.bean);
        if (!fieldNameAndVauleMapping.isEmpty()){
            fieldNameAndVauleMapping.forEach((k,v)->{
                if (matchPhrase==true){
                    boolQuery.must(QueryBuilders.matchPhraseQuery(k,v));
                }else{
                    boolQuery.must(QueryBuilders.matchQuery(k,v));
                }
            });
        }
    }
    searchRequestBuilder.setQuery(QueryBuilders.matchAllQuery());
    searchRequestBuilder.setQuery(boolQuery);
    // 设置是否按查询匹配度排序
    searchRequestBuilder.setExplain(true);
    SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
    long totalHits = searchResponse.getHits().totalHits;
    long length = searchResponse.getHits().getHits().length;
    logger.debug("共查询到[{}]条数据,处理数据条数[{}]", totalHits, length);
    return searchResponse(searchResponse,null);
}
 
Example 8
Source File: EsQuery.java    From AsuraFramework with Apache License 2.0 4 votes vote down vote up
private SearchRequestBuilder buildSearchRequest (EsQueryDo esQueryObj) throws  EsException {
    if (Check.NuNStrStrict(esClientFactory.getIndexs(esQueryObj.getIndexName()))) {
        throw new EsException("没有指定要搜索的索引名称(indexName)");
    }
    for (ThreadPoolStats.Stats stats : esClientFactory.getClient().threadPool().stats()) {
        logger.info(JSON.toJSONString(stats));
    }
    //加载要搜索索引
    SearchRequestBuilder searchRequestBuilder = esClientFactory.getClient().prepareSearch(esClientFactory.getIndexs(esQueryObj.getIndexName()));
    //由spring从配置加载要搜索的index的类型
    searchRequestBuilder.setTypes(esQueryObj.getTypeName());
    //由spring从配置加载要搜索的类型
    searchRequestBuilder.setSearchType(SearchType.fromId(esQueryObj.getSearchType()));
    //查询可以为null
    searchRequestBuilder.setQuery(esQueryObj.getQueryBuilder());

    if (!Check.NuNCollection(esQueryObj.getSortBuilders())) {
        for (SortBuilder sortBuilder : esQueryObj.getSortBuilders()) {
            searchRequestBuilder.addSort(sortBuilder);
        }
    }
    if (!Check.NuNCollection(esQueryObj.getAggregationBuilders())) {
        for (AbstractAggregationBuilder aggregationBuilder : esQueryObj.getAggregationBuilders()) {
            searchRequestBuilder.addAggregation(aggregationBuilder);
        }

    }
    //设置高亮域
   if (esQueryObj.isHighLigth()) {
        if (!Check.NuNObject(esQueryObj.highLigthFields())) {
            for (String hlFieldName : esQueryObj.highLigthFields()) {
                searchRequestBuilder.addHighlightedField(hlFieldName).setHighlighterPreTags(esQueryObj.getHighLigthPreTag())
                        .setHighlighterPostTags(esQueryObj.getHighLigthPostTag());
            }
        }
    }
    //分页
    searchRequestBuilder.setFrom(esQueryObj.getFromIndex()).setSize(esQueryObj.getSize());
    searchRequestBuilder.setExplain(esQueryObj.isExplain());
    return searchRequestBuilder;
}
 
Example 9
Source File: EsSearch.java    From es-service-parent with Apache License 2.0 4 votes vote down vote up
/**
 * 搜索入口
 * 
 * @param request
 * @param timeout
 * @param timeUnit
 * @return
 */
public static EsResponse search(EsRequest request, int timeout, TimeUnit timeUnit) {
    // 索引
    String indexname = request.getIndexname();
    // 结束位置
    int size = request.getPs();
    // 开始位置
    int from = request.getPn() < 0 ? 0 : (request.getPn() - 1) * size;

    // 主查询体
    SearchRequestBuilder srb = ESClient.getClient().prepareSearch(indexname)
            .setTypes(request.getTypes().toArray(new String[] {})).setFrom(from).setSize(size)
            .setPreference(Constants.preference).setTimeout(new TimeValue(timeout, timeUnit));

    // 构造查询体
    EsQueryBuilder esQueryBuilder = new EsQueryBuilder(request);
    esQueryBuilder.makeFilterBuilder(srb);
    if (esQueryBuilder.makeQueryBuilder(srb) == null) {
        return new EsResponse();
    }

    // 处理返回字段
    if (!request.getSafeResultFileds().isEmpty()) {
        srb.addFields(request.getSafeResultFileds().toArray(new String[] {}));
    }
    // 高亮
    EsHighLight.setHighLight(srb, request.getSafeHighlightFields());
    // 排序
    EsSort.sortAdapter(srb, request.getSafeSortFileds());
    // 调试模式
    if (Constants.isDebug) {
        srb.setExplain(true);
        logger.info("\r\n" + srb.toString());
    }

    // 返回结果
    SearchResponse response = srb.execute().actionGet();
    List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
    for (SearchHit hit : response.getHits()) {
        Map<String, Object> record = hit.getSource();
        if (record == null && (record = new HashMap<String, Object>()) != null) {
            for (Map.Entry<String, SearchHitField> e : hit.fields().entrySet()) {
                record.put(e.getKey(), e.getValue().getValue());
            }
        }
        record.put("ESSCORE", hit.getScore());
        // 高亮返回
        if (request.getSafeHighlightFields() != null) {
            record.putAll(EsHighLight.getHighlight(hit, request.getSafeHighlightFields()
                    .getFields()));
        }
        result.add(record);
    }

    // 调试模式
    if (Constants.isDebug) {
        logger.info("search result :{}", JsonUtil.toJson(result));
        logger.info("search TotalHits :{}", response.getHits().getTotalHits());
        logger.info("search TookInMillis :{}", response.getTookInMillis());
    }

    logger.info("search log for index:{},keys:{}", indexname, request.getAllValue());
    return new EsResponse((int) response.getHits().getTotalHits(), JsonUtil.toJson(result), 0);
}