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


Java FieldSortBuilder类代码示例

本文整理汇总了Java中org.elasticsearch.search.sort.FieldSortBuilder的典型用法代码示例。如果您正苦于以下问题:Java FieldSortBuilder类的具体用法?Java FieldSortBuilder怎么用?Java FieldSortBuilder使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


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

示例1: getTopicByCateAndUser

import org.elasticsearch.search.sort.FieldSortBuilder; //导入依赖的package包/类
@Override
public FacetedPage<Topic> getTopicByCateAndUser(String cate  , String q , String user ,final int p , final int ps) {

	FacetedPage<Topic> pages  = null ;
	NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(termQuery("cate" , cate)).withQuery(termQuery("creater" , user)).withSort(new FieldSortBuilder("top").unmappedType("boolean").order(SortOrder.DESC)).withSort(new FieldSortBuilder("updatetime").unmappedType("date").order(SortOrder.DESC));
	
	if(!StringUtils.isBlank(q)){
	   	searchQueryBuilder.withQuery(new QueryStringQueryBuilder(q).defaultOperator(Operator.AND)) ;
	}
	SearchQuery searchQuery = searchQueryBuilder.build().setPageable(new PageRequest(p, ps));
	if(elasticsearchTemplate.indexExists(Topic.class)){
    	
		if(!StringUtils.isBlank(q)){
    		pages = elasticsearchTemplate.queryForPage(searchQuery, Topic.class, new UKResultMapper());
    	}else{
    		pages = elasticsearchTemplate.queryForPage(searchQuery, Topic.class);
    	}
    }
    return pages ; 
}
 
开发者ID:uckefu,项目名称:uckefu,代码行数:21,代码来源:TopicRepositoryImpl.java

示例2: executeRequest

import org.elasticsearch.search.sort.FieldSortBuilder; //导入依赖的package包/类
/**
 * Execute query request with filter and aggregations.
 * 
 * @param query
 *            search query
 * @return ES search response
 * @throws ODataApplicationException
 *             if any error appeared during executing request
 */
public SearchResponse executeRequest(SearchQuery query) throws ODataApplicationException {
    Pagination pagination = query.getPagination();
    SearchRequestBuilder requestBuilder = client.prepareSearch(query.getIndex())
            .setTypes(query.getTypes()).setQuery(query.getQueryBuilder());
    if (pagination != null) {
        List<Sort> orderBy = pagination.getOrderBy();
        for (Sort sort : orderBy) {
            FieldSortBuilder sortQuery = SortBuilders.fieldSort(sort.getProperty())
                    .order(SortOrder.valueOf(sort.getDirection().toString()));
            requestBuilder.addSort(sortQuery);
        }
        requestBuilder.setSize(pagination.getTop()).setFrom(pagination.getSkip());
    }
    Set<String> fields = query.getFields();
    if (fields != null && !fields.isEmpty()) {
        requestBuilder.setFetchSource(fields.toArray(new String[fields.size()]), null);
    }
    return executeRequest(requestBuilder);
}
 
开发者ID:Hevelian,项目名称:hevelian-olastic,代码行数:29,代码来源:ESClient.java

示例3: getDocumentUsingScroll

import org.elasticsearch.search.sort.FieldSortBuilder; //导入依赖的package包/类
/**
 * This method used to get the document using scroll concept
 */
@Override
public void getDocumentUsingScroll() {
    try {
        client = ESclient.getInstant();
        QueryBuilder qb = termQuery("name", "sundar");
        SearchResponse scrollResp = client.prepareSearch("school", "college")
                .addSort(FieldSortBuilder.DOC_FIELD_NAME, SortOrder.ASC)
                .setScroll(new TimeValue(60000))
                .setQuery(qb)
                .setSize(100).get(); //max of 100 hits will be returned for each scroll, Scroll until no hits are returned
        do {
            for (SearchHit hit : scrollResp.getHits().getHits()) {
                //Handle the hit...
                hit.getField("name");
            }

            scrollResp = client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(60000)).execute().actionGet();
        } while (scrollResp.getHits().getHits().length != 0); // Zero hits mark the end of the scroll and the while loop.
    } catch (Exception ex) {
        log.info("Exception occurred while Scroll Document : " + ex);
    }
}
 
开发者ID:sundarcse1216,项目名称:es-crud,代码行数:26,代码来源:SearchAPIExampleImpl.java

示例4: testThatSortingOnCompletionFieldReturnsUsefulException

import org.elasticsearch.search.sort.FieldSortBuilder; //导入依赖的package包/类
public void testThatSortingOnCompletionFieldReturnsUsefulException() throws Exception {
    createIndexAndMapping(completionMappingBuilder);

    client().prepareIndex(INDEX, TYPE, "1").setSource(jsonBuilder()
            .startObject().startObject(FIELD)
            .startArray("input").value("Nirvana").endArray()
            .endObject().endObject()
    ).get();

    refresh();
    try {
        client().prepareSearch(INDEX).setTypes(TYPE).addSort(new FieldSortBuilder(FIELD)).execute().actionGet();
        fail("Expected an exception due to trying to sort on completion field, but did not happen");
    } catch (SearchPhaseExecutionException e) {
        assertThat(e.status().getStatus(), is(400));
        assertThat(e.toString(), containsString("Fielddata is not supported on field [" + FIELD + "] of type [completion]"));
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:19,代码来源:CompletionSuggestSearchIT.java

示例5: doCreateTestQueryBuilder

import org.elasticsearch.search.sort.FieldSortBuilder; //导入依赖的package包/类
/**
 * @return a {@link HasChildQueryBuilder} with random values all over the place
 */
@Override
protected HasChildQueryBuilder doCreateTestQueryBuilder() {
    int min = randomIntBetween(0, Integer.MAX_VALUE / 2);
    int max = randomIntBetween(min, Integer.MAX_VALUE);

    QueryBuilder innerQueryBuilder = RandomQueryBuilder.createQuery(random());
    if (randomBoolean()) {
        requiresRewrite = true;
        innerQueryBuilder = new WrapperQueryBuilder(innerQueryBuilder.toString());
    }

    HasChildQueryBuilder hqb = new HasChildQueryBuilder(CHILD_TYPE, innerQueryBuilder,
            RandomPicks.randomFrom(random(), ScoreMode.values()));
    hqb.minMaxChildren(min, max);
    hqb.ignoreUnmapped(randomBoolean());
    if (randomBoolean()) {
        hqb.innerHit(new InnerHitBuilder()
                .setName(randomAsciiOfLengthBetween(1, 10))
                .setSize(randomIntBetween(0, 100))
                .addSort(new FieldSortBuilder(STRING_FIELD_NAME_2).order(SortOrder.ASC)), hqb.ignoreUnmapped());
    }
    return hqb;
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:27,代码来源:HasChildQueryBuilderTests.java

示例6: doCreateTestQueryBuilder

import org.elasticsearch.search.sort.FieldSortBuilder; //导入依赖的package包/类
/**
 * @return a {@link HasChildQueryBuilder} with random values all over the place
 */
@Override
protected NestedQueryBuilder doCreateTestQueryBuilder() {
    QueryBuilder innerQueryBuilder = RandomQueryBuilder.createQuery(random());
    if (randomBoolean()) {
        requiresRewrite = true;
        innerQueryBuilder = new WrapperQueryBuilder(innerQueryBuilder.toString());
    }
    NestedQueryBuilder nqb = new NestedQueryBuilder("nested1", innerQueryBuilder,
            RandomPicks.randomFrom(random(), ScoreMode.values()));
    nqb.ignoreUnmapped(randomBoolean());
    if (randomBoolean()) {
        nqb.innerHit(new InnerHitBuilder()
                .setName(randomAsciiOfLengthBetween(1, 10))
                .setSize(randomIntBetween(0, 100))
                .addSort(new FieldSortBuilder(INT_FIELD_NAME).order(SortOrder.ASC)), nqb.ignoreUnmapped());
    }
    return nqb;
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:22,代码来源:NestedQueryBuilderTests.java

示例7: doCreateTestQueryBuilder

import org.elasticsearch.search.sort.FieldSortBuilder; //导入依赖的package包/类
/**
 * @return a {@link HasChildQueryBuilder} with random values all over the place
 */
@Override
protected HasParentQueryBuilder doCreateTestQueryBuilder() {
    QueryBuilder innerQueryBuilder = RandomQueryBuilder.createQuery(random());
    if (randomBoolean()) {
        requiresRewrite = true;
        innerQueryBuilder = new WrapperQueryBuilder(innerQueryBuilder.toString());
    }
    HasParentQueryBuilder hqb = new HasParentQueryBuilder(PARENT_TYPE, innerQueryBuilder, randomBoolean());
    hqb.ignoreUnmapped(randomBoolean());
    if (randomBoolean()) {
        hqb.innerHit(new InnerHitBuilder()
                .setName(randomAsciiOfLengthBetween(1, 10))
                .setSize(randomIntBetween(0, 100))
                .addSort(new FieldSortBuilder(STRING_FIELD_NAME_2).order(SortOrder.ASC)), hqb.ignoreUnmapped());
    }
    return hqb;
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:21,代码来源:HasParentQueryBuilderTests.java

示例8: getTopFilmes

import org.elasticsearch.search.sort.FieldSortBuilder; //导入依赖的package包/类
public List<Map<String, Object>> getTopFilmes() {

		List<Map<String, Object>> filmes = new ArrayList<Map<String, Object>>();
		// Seu código deve vir daqui para baixo

		FieldSortBuilder sort = new FieldSortBuilder("vote_average").order(SortOrder.DESC);

		SearchResponse response = client.prepareSearch(INDEX).setTypes(TYPE).addSort(sort).execute().actionGet();

		SearchHit[] results = response.getHits().getHits();
		
		for (SearchHit hit : results) {
			System.out.println("------------------------------");
			Map<String, Object> result = hit.getSourceAsMap();
			filmes.add(result);
			System.out.println(result);
		}
		
		return filmes;
	}
 
开发者ID:wilkerjmachado,项目名称:MoviesSearchPos,代码行数:21,代码来源:Filmes.java

示例9: useScrollIfNeeded

import org.elasticsearch.search.sort.FieldSortBuilder; //导入依赖的package包/类
private boolean useScrollIfNeeded(boolean existsOrderBy) {
	Hint scrollHint = null;
	for (Hint hint : select.getHints()) {
		if (hint.getType() == HintType.USE_SCROLL) {
			scrollHint = hint;
			break;
		}
	}
	if (scrollHint != null) {
		int scrollSize = (Integer) scrollHint.getParams()[0];
		int timeoutInMilli = (Integer) scrollHint.getParams()[1];
		if (!existsOrderBy)
			request.addSort(FieldSortBuilder.DOC_FIELD_NAME, SortOrder.ASC);
		request.setScroll(new TimeValue(timeoutInMilli)).setSize(scrollSize);
	}
	return scrollHint != null;
}
 
开发者ID:mazhou,项目名称:es-sql,代码行数:18,代码来源:DefaultQueryAction.java

示例10: buildSort

import org.elasticsearch.search.sort.FieldSortBuilder; //导入依赖的package包/类
@SuppressWarnings({ "rawtypes" })
private SortBuilder[] buildSort(UAVHttpMessage data) {

    SortBuilder[] sorts = null;

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

    if (sort != null) {
        String[] sortFieldStrs = sort.split(",");
        List<SortBuilder> ls = new ArrayList<SortBuilder>();
        for (String sortFieldStr : sortFieldStrs) {
            String[] sortExp = sortFieldStr.split("=");
            SortBuilder stimeSort = new FieldSortBuilder(sortExp[0]);
            stimeSort.order(SortOrder.fromString(sortExp[1]));
            ls.add(stimeSort);
        }
        sorts = new SortBuilder[ls.size()];
        sorts = ls.toArray(sorts);
    }
    else {
        return null;
    }
    return sorts;
}
 
开发者ID:uavorg,项目名称:uavstack,代码行数:25,代码来源:SlowOperQueryHandler.java

示例11: getMostRecentEntry

import org.elasticsearch.search.sort.FieldSortBuilder; //导入依赖的package包/类
/**
 * Gets the creation data of the single newest entry.
 *
 * @return ISO8601 formatted time of most recent entry, or null on empty or error.
 */
private String getMostRecentEntry() {
    long totalEntries = client.prepareCount(index).setQuery(matchAllQuery()).execute().actionGet().getCount();
    if (totalEntries > 0) {
        FilteredQueryBuilder updatedAtQuery = QueryBuilders
                .filteredQuery(QueryBuilders.matchAllQuery(), FilterBuilders.existsFilter("created_at"));
        FieldSortBuilder updatedAtSort = SortBuilders.fieldSort("created_at").order(SortOrder.DESC);

        SearchResponse response = client.prepareSearch(index)
                .setQuery(updatedAtQuery)
                .addSort(updatedAtSort)
                .setSize(1)
                .execute()
                .actionGet();

        String createdAt = (String) response.getHits().getAt(0).getSource().get("created_at");
        logger.debug("Most recent event was created at {}", createdAt);
        return createdAt;
    } else {
        // getData will get all data on a null.
        logger.info("No existing entries, assuming first run");
        return null;
    }
}
 
开发者ID:uberVU,项目名称:elasticsearch-river-github,代码行数:29,代码来源:GitHubRiver.java

示例12: fieldSort

import org.elasticsearch.search.sort.FieldSortBuilder; //导入依赖的package包/类
@Override
public QueryBuilderHelper fieldSort(String fieldName, boolean desc) {
    if (fieldName == null) {
        return this;
    }
    fieldSort = true;
    FieldSortBuilder sortBuilder = SortBuilders.fieldSort(fieldName);
    if (desc) {
        sortBuilder.order(SortOrder.DESC);
    } else {
        sortBuilder.order(SortOrder.ASC);
    }
    // TODO: change to use sortBuilder.unmappedType
    sortBuilder.ignoreUnmapped(true);
    searchRequestBuilder.addSort(sortBuilder);
    return this;
}
 
开发者ID:alien4cloud,项目名称:elasticsearch-mapping-parent,代码行数:18,代码来源:QueryHelper.java

示例13: sortToUri

import org.elasticsearch.search.sort.FieldSortBuilder; //导入依赖的package包/类
private static String sortToUri(SortBuilder<?> sort) {
    if (sort instanceof FieldSortBuilder) {
        FieldSortBuilder f = (FieldSortBuilder) sort;
        return f.getFieldName() + ":" + f.order();
    }
    throw new IllegalArgumentException("Unsupported sort [" + sort + "]");
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:8,代码来源:RemoteRequestBuilders.java

示例14: testStringSortMissingAscTerminates

import org.elasticsearch.search.sort.FieldSortBuilder; //导入依赖的package包/类
public void testStringSortMissingAscTerminates() throws Exception {
    assertAcked(prepareCreate("test")
            .setSettings(Settings.builder().put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1).put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0))
            .addMapping("test", "no_field", "type=keyword", "some_field", "type=keyword"));
    client().prepareIndex("test", "test", "1").setSource("some_field", "test").get();
    refresh();

    SearchResponse response = client().prepareSearch("test")
            .setTypes("test")
            .addSort(new FieldSortBuilder("no_field").order(SortOrder.ASC).missing("_last"))
            .setScroll("1m")
            .get();
    assertHitCount(response, 1);
    assertSearchHits(response, "1");

    response = client().prepareSearchScroll(response.getScrollId()).get();
    assertSearchResponse(response);
    assertHitCount(response, 1);
    assertNoSearchHits(response);

    response = client().prepareSearch("test")
            .setTypes("test")
            .addSort(new FieldSortBuilder("no_field").order(SortOrder.ASC).missing("_first"))
            .setScroll("1m")
            .get();
    assertHitCount(response, 1);
    assertSearchHits(response, "1");

    response = client().prepareSearchScroll(response.getScrollId()).get();
    assertHitCount(response, 1);
    assertThat(response.getHits().getHits().length, equalTo(0));
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:33,代码来源:SearchScrollIT.java

示例15: CopyIndex

import org.elasticsearch.search.sort.FieldSortBuilder; //导入依赖的package包/类
public void CopyIndex(Client sourceclient, String sourceindex, Client targetclient, String targetindex) {
	// TODO Auto-generated method stub
	count = 0;
	QueryBuilder qb = QueryBuilders.matchAllQuery();

	try {

		SearchResponse scrollResp = sourceclient.prepareSearch(sourceindex)
				.addSort(FieldSortBuilder.DOC_FIELD_NAME, SortOrder.ASC).setScroll(new TimeValue(60000))
				.setQuery(qb).setSize(500).execute().actionGet();

		while (true) {
			final BulkRequestBuilder bulkRequest = targetclient.prepareBulk();
			for (SearchHit hit : scrollResp.getHits().getHits()) {
				bulkRequest.add(targetclient.prepareIndex(targetindex, hit.getType().toString(), hit.getId())
						.setSource(hit.getSourceAsString()));
				count++;
			}

			bulkRequest.execute();
			scrollResp = sourceclient.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(60000))
					.execute().actionGet();

			logger.info(count + " documents putted!!");

			if (scrollResp.getHits().getHits().length == 0) {
				break;
			}
		}

		logger.info("copy index " + sourceindex + " " + count + " documents" + " to " + targetindex + " complete");
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
开发者ID:jiashiwen,项目名称:elasticbak,代码行数:37,代码来源:ElasticsearchCopyIndex.java


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