当前位置: 首页>>代码示例>>Java>>正文


Java SearchRequestBuilder.addSort方法代码示例

本文整理汇总了Java中org.elasticsearch.action.search.SearchRequestBuilder.addSort方法的典型用法代码示例。如果您正苦于以下问题:Java SearchRequestBuilder.addSort方法的具体用法?Java SearchRequestBuilder.addSort怎么用?Java SearchRequestBuilder.addSort使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.elasticsearch.action.search.SearchRequestBuilder的用法示例。


在下文中一共展示了SearchRequestBuilder.addSort方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: assertBasicSearchWorks

import org.elasticsearch.action.search.SearchRequestBuilder; //导入方法依赖的package包/类
void assertBasicSearchWorks(String indexName) {
    logger.info("--> testing basic search");
    SearchRequestBuilder searchReq = client().prepareSearch(indexName).setQuery(QueryBuilders.matchAllQuery());
    SearchResponse searchRsp = searchReq.get();
    ElasticsearchAssertions.assertNoFailures(searchRsp);
    long numDocs = searchRsp.getHits().getTotalHits();
    logger.info("Found {} in old index", numDocs);

    logger.info("--> testing basic search with sort");
    searchReq.addSort("long_sort", SortOrder.ASC);
    ElasticsearchAssertions.assertNoFailures(searchReq.get());

    logger.info("--> testing exists filter");
    searchReq = client().prepareSearch(indexName).setQuery(QueryBuilders.existsQuery("string"));
    searchRsp = searchReq.get();
    ElasticsearchAssertions.assertNoFailures(searchRsp);
    assertEquals(numDocs, searchRsp.getHits().getTotalHits());
    GetSettingsResponse getSettingsResponse = client().admin().indices().prepareGetSettings(indexName).get();
    Version versionCreated = Version.fromId(Integer.parseInt(getSettingsResponse.getSetting(indexName, "index.version.created")));
    if (versionCreated.onOrAfter(Version.V_2_4_0)) {
        searchReq = client().prepareSearch(indexName).setQuery(QueryBuilders.existsQuery("field.with.dots"));
        searchRsp = searchReq.get();
        ElasticsearchAssertions.assertNoFailures(searchRsp);
        assertEquals(numDocs, searchRsp.getHits().getTotalHits());
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:27,代码来源:OldIndexBackwardsCompatibilityIT.java

示例2: assertSearchFromWithSortValues

import org.elasticsearch.action.search.SearchRequestBuilder; //导入方法依赖的package包/类
private void assertSearchFromWithSortValues(String indexName, String typeName, List<List> documents, int reqSize) throws Exception {
    int numFields = documents.get(0).size();
    {
        createIndexMappingsFromObjectType(indexName, typeName, documents.get(0));
        List<IndexRequestBuilder> requests = new ArrayList<>();
        for (int i = 0; i < documents.size(); i++) {
            XContentBuilder builder = jsonBuilder();
            assertThat(documents.get(i).size(), Matchers.equalTo(numFields));
            builder.startObject();
            for (int j = 0; j < numFields; j++) {
                builder.field("field" + Integer.toString(j), documents.get(i).get(j));
            }
            builder.endObject();
            requests.add(client().prepareIndex(INDEX_NAME, TYPE_NAME, Integer.toString(i)).setSource(builder));
        }
        indexRandom(true, requests);
    }

    Collections.sort(documents, LST_COMPARATOR);
    int offset = 0;
    Object[] sortValues = null;
    while (offset < documents.size()) {
        SearchRequestBuilder req = client().prepareSearch(indexName);
        for (int i = 0; i < documents.get(0).size(); i++) {
            req.addSort("field" + Integer.toString(i), SortOrder.ASC);
        }
        req.setQuery(matchAllQuery()).setSize(reqSize);
        if (sortValues != null) {
            req.searchAfter(sortValues);
        }
        SearchResponse searchResponse = req.get();
        for (SearchHit hit : searchResponse.getHits()) {
            List toCompare = convertSortValues(documents.get(offset++));
            assertThat(LST_COMPARATOR.compare(toCompare, Arrays.asList(hit.getSortValues())), equalTo(0));
        }
        sortValues = searchResponse.getHits().getHits()[searchResponse.getHits().getHits().length-1].getSortValues();
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:39,代码来源:SearchAfterIT.java

示例3: scrollOneTimeWithHits

import org.elasticsearch.action.search.SearchRequestBuilder; //导入方法依赖的package包/类
public static SearchResponse scrollOneTimeWithHits(Client client, SearchRequestBuilder requestBuilder, Select originalSelect, int resultSize) {
        SearchResponse responseWithHits;SearchRequestBuilder scrollRequest = requestBuilder
                .setScroll(new TimeValue(60000))
                .setSize(resultSize);
        boolean ordered = originalSelect.isOrderdSelect();
        if(!ordered) scrollRequest.addSort(FieldSortBuilder.DOC_FIELD_NAME, SortOrder.ASC);
        responseWithHits = scrollRequest.get();
        //on ordered select - not using SCAN , elastic returns hits on first scroll
        //es5.0 elastic always return docs on scan
//        if(!ordered) {
//            responseWithHits = client.prepareSearchScroll(responseWithHits.getScrollId()).setScroll(new TimeValue(600000)).get();
//        }
        return responseWithHits;
    }
 
开发者ID:mazhou,项目名称:es-sql,代码行数:15,代码来源:ElasticUtils.java

示例4: scrollOneTimeWithMax

import org.elasticsearch.action.search.SearchRequestBuilder; //导入方法依赖的package包/类
protected SearchResponse scrollOneTimeWithMax(Client client,TableInJoinRequestBuilder tableRequest) {
        SearchResponse responseWithHits;SearchRequestBuilder scrollRequest = tableRequest.getRequestBuilder()
                .setScroll(new TimeValue(60000))
                .setSize(MAX_RESULTS_ON_ONE_FETCH);
        boolean ordered = tableRequest.getOriginalSelect().isOrderdSelect();
        if(!ordered) scrollRequest.addSort(FieldSortBuilder.DOC_FIELD_NAME, SortOrder.ASC);
        responseWithHits = scrollRequest.get();
        //on ordered select - not using SCAN , elastic returns hits on first scroll
        //es5.0 elastic always return docs on scan
//        if(!ordered)
//            responseWithHits = client.prepareSearchScroll(responseWithHits.getScrollId()).setScroll(new TimeValue(600000)).get();
        return responseWithHits;
    }
 
开发者ID:mazhou,项目名称:es-sql,代码行数:14,代码来源:ElasticJoinExecutor.java

示例5: query

import org.elasticsearch.action.search.SearchRequestBuilder; //导入方法依赖的package包/类
@SuppressWarnings("rawtypes")
private SearchResponse query(UAVHttpMessage data, QueryBuilder queryBuilder, QueryBuilder postFilter,
        List<SortBuilder> sorts) {

    String date = data.getRequest("indexdate");
    String currentIndex;
    if (date != null) {
        // 指定index
        currentIndex = this.indexMgr.getIndexByDate(date);
    }
    else {
        // current index
        currentIndex = this.indexMgr.getCurrentIndex();
    }

    SearchRequestBuilder srb = client.getClient().prepareSearch(currentIndex)
            .setTypes(ThreadAnalysisIndexMgr.JTA_TABLE).setSearchType(SearchType.DFS_QUERY_THEN_FETCH);

    int from = DataConvertHelper.toInt(data.getRequest("from"), -1);
    int size = DataConvertHelper.toInt(data.getRequest("size"), -1);

    if (from != -1 && size != -1) {
        srb = srb.setFrom(from).setSize(size);
    }

    srb.setQuery(queryBuilder);

    if (postFilter != null) {
        srb.setPostFilter(postFilter);
    }

    for (SortBuilder sb : sorts) {
        srb.addSort(sb);
    }

    SearchResponse sr = srb.get(TimeValue.timeValueMillis(timeout));

    return sr;
}
 
开发者ID:uavorg,项目名称:uavstack,代码行数:40,代码来源:ThreadAnalysisQueryHandler.java

示例6: search

import org.elasticsearch.action.search.SearchRequestBuilder; //导入方法依赖的package包/类
/**
 * 查询
 *
 * @param queryBuilder
 * @param type
 * @param sortField    排序字段
 * @param desc
 * @param from         分页起始偏移量
 * @param size         页面大小
 * @return
 */
private static <T> Pagination<T> search(QueryBuilder queryBuilder, IndexType type, String sortField, boolean desc, int from, int size) {
    List<T> results = new ArrayList<>();
    //不同的索引 变量 代码通用
    SearchRequestBuilder serachBuilder = EsClientManager.getClient().prepareSearch(esprop.getIndice())
            .setTypes(type.getDataName())
            .setQuery(queryBuilder);
    if (!StringUtils.isEmpty(sortField)) {
        if (sortField.equalsIgnoreCase(SortMode.ORDERVALUE_ASC.getSortField())) {
            serachBuilder.addSort("_score", SortOrder.DESC);
        }
        serachBuilder.addSort(sortField, desc ? SortOrder.DESC : SortOrder.ASC);
    }
    if (0 != size) {
        serachBuilder.setFrom(from).setSize(size);
    }
    SearchResponse response = serachBuilder.execute().actionGet();
    SearchHits searchHits = response.getHits();
    SearchHit[] hits = searchHits.getHits();
    for (SearchHit hit : hits) {
        results.add((T) EsDataUtil.readValue(hit.source(), type.getTypeClass()));
    }
    int total = (int) searchHits.getTotalHits();
    Pagination pagination = new Pagination();
    pagination.setDataList(results);
    pagination.setTotalCount(total);
    return pagination;
}
 
开发者ID:wxz1211,项目名称:dooo,代码行数:39,代码来源:IndexManager.java

示例7: configureSorting

import org.elasticsearch.action.search.SearchRequestBuilder; //导入方法依赖的package包/类
private static void configureSorting(UriInfo uriInfo, SearchRequestBuilder searchRequest) {
  if (uriInfo.getOrderByOption() == null) {
    return;
  }

  for (OrderByItem orderByItem : uriInfo.getOrderByOption().getOrders()) {
    searchRequest.addSort(
        MemberMapper.toFieldName((Member) orderByItem.getExpression()),
        orderByItem.isDescending() ? SortOrder.DESC : SortOrder.ASC);
  }
}
 
开发者ID:pukkaone,项目名称:odata-spring-boot-starter,代码行数:12,代码来源:EntityRepository.java

示例8: applySort

import org.elasticsearch.action.search.SearchRequestBuilder; //导入方法依赖的package包/类
protected void applySort(SearchRequestBuilder q) {
    for (SortContainer sortContainer : getParameters().getSortContainers()) {
        SortOrder esOrder = sortContainer.direction == SortDirection.ASCENDING ? SortOrder.ASC : SortOrder.DESC;
        if (Element.ID_PROPERTY_NAME.equals(sortContainer.propertyName)) {
            q.addSort("_uid", esOrder);
        } else if (Edge.LABEL_PROPERTY_NAME.equals(sortContainer.propertyName)) {
            q.addSort(Elasticsearch5SearchIndex.EDGE_LABEL_FIELD_NAME, esOrder);
        } else {
            PropertyDefinition propertyDefinition = getGraph().getPropertyDefinition(sortContainer.propertyName);
            if (propertyDefinition == null) {
                continue;
            }
            if (!getSearchIndex().isPropertyInIndex(getGraph(), sortContainer.propertyName)) {
                continue;
            }
            if (!propertyDefinition.isSortable()) {
                throw new MemgraphException("Cannot sort on non-sortable fields");
            }

            String[] propertyNames = getPropertyNames(propertyDefinition.getPropertyName());
            if (propertyNames.length > 1) {
                String scriptSrc = "def fieldValues = []; for (def fieldName : params.fieldNames) { fieldValues.addAll(doc[fieldName].values); } " +
                        "if (params.esOrder == 'asc') { Collections.sort(fieldValues); } else { Collections.sort(fieldValues, Collections.reverseOrder()); }" +
                        "if (params.dataType == 'String') { return fieldValues; } else { return fieldValues.length > 0 ? fieldValues[0] : (params.esOrder == 'asc' ? Integer.MAX_VALUE : Integer.MIN_VALUE); }";

                List<String> fieldNames = Arrays.stream(propertyNames).map(propertyName ->
                        propertyName + (propertyDefinition.getDataType() == String.class ? Elasticsearch5SearchIndex.EXACT_MATCH_PROPERTY_NAME_SUFFIX : "")
                ).collect(Collectors.toList());
                HashMap<String, Object> scriptParams = new HashMap<>();
                scriptParams.put("fieldNames", fieldNames);
                scriptParams.put("esOrder", esOrder == SortOrder.DESC ? "desc" : "asc");
                scriptParams.put("dataType", propertyDefinition.getDataType().getSimpleName());
                Script script = new Script(ScriptType.INLINE, "painless", scriptSrc, scriptParams);
                ScriptSortBuilder.ScriptSortType sortType = propertyDefinition.getDataType() == String.class ? ScriptSortBuilder.ScriptSortType.STRING : ScriptSortBuilder.ScriptSortType.NUMBER;
                q.addSort(SortBuilders.scriptSort(script, sortType)
                        .order(esOrder)
                        .sortMode(esOrder == SortOrder.DESC ? SortMode.MAX : SortMode.MIN));
            } else {
                String sortField = propertyNames[0];
                if (propertyDefinition.getDataType() == String.class) {
                    sortField += Elasticsearch5SearchIndex.EXACT_MATCH_PROPERTY_NAME_SUFFIX;
                }
                q.addSort(sortField, esOrder);
            }
        }
    }
}
 
开发者ID:mware-solutions,项目名称:memory-graph,代码行数:48,代码来源:ElasticsearchSearchQueryBase.java

示例9: searchQueryRaw

import org.elasticsearch.action.search.SearchRequestBuilder; //导入方法依赖的package包/类
/**
 * Executes an ElasticSearch query. This is the core method of the class.
 * @param appid name of the {@link com.erudika.para.core.App}
 * @param type type of object
 * @param query the search query builder
 * @param pager a {@link com.erudika.para.utils.Pager}
 * @return a list of search results
 */
protected SearchHits searchQueryRaw(String appid, String type, QueryBuilder query, Pager... pager) {
	if (StringUtils.isBlank(appid)) {
		return null;
	}
	Pager page = ElasticSearchUtils.getPager(pager);
	SortOrder order = page.isDesc() ? SortOrder.DESC : SortOrder.ASC;
	int max = page.getLimit();
	int pageNum = (int) page.getPage();
	int start = (pageNum < 1 || pageNum > Config.MAX_PAGES) ? 0 : (pageNum - 1) * max;

	if (query == null) {
		query = matchAllQuery();
	}
	if (!StringUtils.isBlank(type)) {
		query = boolQuery().must(query).must(termQuery(Config._TYPE, type));
	}

	SearchHits hits = null;

	try {
		SearchRequestBuilder srb = client().prepareSearch(getIndexName(appid)).
				setSearchType(SearchType.DFS_QUERY_THEN_FETCH).
				setQuery(query).
				setSize(max);

		if (pageNum <= 1 && !StringUtils.isBlank(page.getLastKey())) {
			srb.searchAfter(new Object[]{NumberUtils.toLong(page.getLastKey())});
			srb.setFrom(0);
			srb.addSort(SortBuilders.fieldSort("_docid").order(order));
		} else {
			srb.setFrom(start);
			for (SortBuilder<?> sortField : ElasticSearchUtils.getSortFieldsFromPager(page)) {
				srb.addSort(sortField);
			}
		}

		logger.debug("Elasticsearch query: {}", srb.toString());

		hits = srb.execute().actionGet().getHits();
		page.setCount(hits.getTotalHits());
		if (hits.getHits().length > 0) {
			Object id = hits.getAt(hits.getHits().length - 1).getSourceAsMap().get("_docid");
			if (id != null) {
				page.setLastKey(id.toString());
			}
		}
	} catch (Exception e) {
		Throwable cause = e.getCause();
		String msg = cause != null ? cause.getMessage() : e.getMessage();
		logger.warn("No search results for type '{}' in app '{}': {}.", type, appid, msg);
	}

	return hits;
}
 
开发者ID:Erudika,项目名称:para-search-elasticsearch,代码行数:63,代码来源:ElasticSearch.java

示例10: buildSearchRequest

import org.elasticsearch.action.search.SearchRequestBuilder; //导入方法依赖的package包/类
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;
}
 
开发者ID:AsuraTeam,项目名称:asura,代码行数:42,代码来源:EsQuery.java

示例11: query

import org.elasticsearch.action.search.SearchRequestBuilder; //导入方法依赖的package包/类
/**
 * 
 * @param data
 * @param queryBuilder
 * @param postFilter
 * @return
 */
@SuppressWarnings("rawtypes")
private SearchResponse query(UAVHttpMessage data, QueryBuilder queryBuilder, QueryBuilder postFilter,
        SortBuilder[] sorts) {

    String date = data.getRequest("indexdate");
    String currentIndex;
    if (date != null) {
        // 指定index
        currentIndex = this.indexMgr.getIndexByDate(date);
    }
    else {
        // current index
        currentIndex = this.indexMgr.getCurrentIndex();
    }

    SearchRequestBuilder srb = client.getClient().prepareSearch(currentIndex)
            .setTypes(InvokeChainIndexMgr.IVC_Table).setSearchType(SearchType.DFS_QUERY_THEN_FETCH);

    int from = DataConvertHelper.toInt(data.getRequest("from"), -1);
    int size = DataConvertHelper.toInt(data.getRequest("size"), -1);

    if (from != -1 && size != -1) {
        srb = srb.setFrom(from).setSize(size);
    }

    srb.setQuery(queryBuilder);

    if (postFilter != null) {
        srb.setPostFilter(postFilter);
    }

    if (sorts != null && sorts.length > 0) {
        for (SortBuilder sb : sorts) {
            srb.addSort(sb);
        }
    }

    SearchResponse sr = srb.get(TimeValue.timeValueMillis(timeout));

    return sr;
}
 
开发者ID:uavorg,项目名称:uavstack,代码行数:49,代码来源:InvokeChainQueryHandler.java

示例12: query

import org.elasticsearch.action.search.SearchRequestBuilder; //导入方法依赖的package包/类
@SuppressWarnings("rawtypes")
private SearchResponse query(UAVHttpMessage data, QueryBuilder queryBuilder, QueryBuilder postFilter,
        SortBuilder[] sorts) {

    String appid = data.getRequest("appid");
    if (appid == null) {
        data.putResponse("rs", "ERR");
        data.putResponse("msg", "appid is required");
        return null;
    }

    String indexDate = data.getRequest("indexdate");
    String currentIndex;
    if (indexDate != null) {
        // 获得指定的index
        currentIndex = this.indexMgr.getIndexByDate(indexDate, appid);
    }
    else {
        // get current index
        currentIndex = this.indexMgr.getCurrentIndex(appid);
    }

    SearchRequestBuilder srb = client.getClient().prepareSearch(currentIndex).setTypes(buildTypes(data))
            .setSearchType(SearchType.DFS_QUERY_THEN_FETCH);

    int from = DataConvertHelper.toInt(data.getRequest("from"), -1);
    int size = DataConvertHelper.toInt(data.getRequest("size"), -1);

    if (from != -1 && size != -1) {
        srb = srb.setFrom(from).setSize(size);
    }

    srb.setQuery(queryBuilder);

    if (postFilter != null) {
        srb.setPostFilter(postFilter);
    }

    if (sorts != null && sorts.length > 0) {
        for (SortBuilder sb : sorts) {
            srb.addSort(sb);
        }
    }

    SearchResponse sr = srb.get(TimeValue.timeValueMillis(timeout));

    return sr;
}
 
开发者ID:uavorg,项目名称:uavstack,代码行数:49,代码来源:SlowOperQueryHandler.java

示例13: query

import org.elasticsearch.action.search.SearchRequestBuilder; //导入方法依赖的package包/类
@SuppressWarnings("rawtypes")
private SearchResponse query(UAVHttpMessage data, QueryBuilder queryBuilder, QueryBuilder postFilter,
        SortBuilder[] sorts) {

    String appid = data.getRequest("appid");

    String indexDate = data.getRequest("indexdate");
    String currentIndex;
    if (indexDate != null) {
        // 获得指定的index
        currentIndex = this.indexMgr.getIndexByDate(indexDate, appid);
    }
    else {
        // get current index
        currentIndex = this.indexMgr.getCurrentIndex(appid);
    }

    // get logtype for search
    SearchRequestBuilder srb = null;
    if (StringHelper.isEmpty(data.getRequest("logtype"))) {

        srb = client.getClient().prepareSearch(currentIndex).setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
    }
    else {
        String logType = data.getRequest("logtype").replace('.', '_');

        srb = client.getClient().prepareSearch(currentIndex).setTypes(logType)
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
    }

    int from = DataConvertHelper.toInt(data.getRequest("from"), -1);
    int size = DataConvertHelper.toInt(data.getRequest("size"), -1);

    if (from != -1 && size != -1) {
        long startLine = DataConvertHelper.toLong(data.getRequest("sline"), -1);
        long endLine = DataConvertHelper.toLong(data.getRequest("eline"), -1);
        // 判断如果只有endline则需要将结果倒序,取其前100行,然后在返回响应时再逆序回来,从而取到endline前的100行
        if (startLine == -1 && endLine > -1) {
            srb = srb.addSort("l_timestamp", SortOrder.DESC).addSort("l_num", SortOrder.DESC).setFrom(from)
                    .setSize(size);
        }
        else {
            srb = srb.setFrom(from).setSize(size);
        }
    }

    srb.setQuery(queryBuilder);

    if (postFilter != null) {
        srb.setPostFilter(postFilter);
    }

    if (sorts != null && sorts.length > 0) {
        for (SortBuilder sb : sorts) {
            srb.addSort(sb);
        }
    }

    SearchResponse sr = srb.get(TimeValue.timeValueMillis(timeout));

    return sr;
}
 
开发者ID:uavorg,项目名称:uavstack,代码行数:63,代码来源:NewLogQueryHandler.java

示例14: queryForObject

import org.elasticsearch.action.search.SearchRequestBuilder; //导入方法依赖的package包/类
/**
 * 查询返回一个Map对象
 *
 * @param esIndexName
 * @param type
 * @param fields
 * @param content
 * @param sortField
 * @param order
 * @param from
 * @param size
 * @return
 */

public List<Map<String, Object>> queryForObject(String esIndexName, String type, String[] fields, String content, String sortField, SortOrder order, List<String> heightFields, int from, int size) {
    SearchRequestBuilder reqBuilder = esClient.prepareSearch(esIndexName)
            .setTypes(type).setSearchType(SearchType.DEFAULT)
            .setExplain(true);
    QueryStringQueryBuilder queryString = QueryBuilders.queryStringQuery("\"" + content + "\"");
    for (String k : fields) {
        queryString.field(k);
    }
    queryString.minimumShouldMatch("10");
    reqBuilder.setExplain(true);

    reqBuilder.setQuery(QueryBuilders.boolQuery().should(queryString))
            .setExplain(true);
    if (StringUtils.isNotEmpty(sortField) && order != null) {
        reqBuilder.addSort(sortField, order);
    }
    if (from >= 0 && size > 0) {
        reqBuilder.setFrom(from).setSize(size);
    }
    //设置高亮显示
    if (heightFields != null) {
        for (String hs : heightFields)
            reqBuilder.addHighlightedField(hs);
    }
    reqBuilder.setHighlighterPreTags("<span style=\"color:red\">");
    reqBuilder.setHighlighterPostTags("</span>");
    SearchResponse resp = reqBuilder.execute().actionGet();
    SearchHit[] hits = resp.getHits().getHits();

    List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
    for (SearchHit hit : hits) {
        Map<String, Object> map = new HashMap<String, Object>();
        for (String key : hit.getSource().keySet()) {
            if (heightFields != null && heightFields.contains(key)) {
                map.put(key, hit.getHighlightFields().get(key).fragments()[0]);
            } else
                map.put(key, hit.getSource().get(key));

        }
        results.add(map);
    }
    return results;
}
 
开发者ID:aillamsun,项目名称:spring-boot-elastcsearch-example,代码行数:58,代码来源:EsNotEntityDao.java


注:本文中的org.elasticsearch.action.search.SearchRequestBuilder.addSort方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。