org.elasticsearch.search.sort.SortBuilders Java Examples
The following examples show how to use
org.elasticsearch.search.sort.SortBuilders.
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: QueryOrderByParser.java From elasticsearch-sql with MIT License | 7 votes |
@Override public void parse(ElasticDslContext dslContext) { if(dslContext.getSqlContext().selectOperation()!=null&&dslContext.getSqlContext().selectOperation().groupByClause()==null){ if(dslContext.getSqlContext().selectOperation().orderClause()!=null){ ElasticsearchParser.OrderClauseContext orderClauseContext=dslContext.getSqlContext().selectOperation().orderClause(); for(ElasticsearchParser.OrderContext orderContext:orderClauseContext.order()){ ElasticsearchParser.NameClauseContext nameContext = orderContext.nameClause(); if(nameContext instanceof ElasticsearchParser.FieldNameContext){ ElasticsearchParser.FieldNameContext fieldNameContext=(ElasticsearchParser.FieldNameContext)nameContext; String field = fieldNameContext.field.getText(); if(fieldNameContext.highlighter!=null){ dslContext.getParseResult().getHighlighter().add(field); } SortOrder sortOrder; if(orderContext.ASC()!=null) { sortOrder=SortOrder.ASC; }else{ sortOrder=SortOrder.DESC; } SortBuilder sortBuilder = SortBuilders.fieldSort(field).sortMode(SortMode.AVG).order(sortOrder); dslContext.getParseResult().getOrderBy().add(sortBuilder); } } } } }
Example #2
Source File: ShellScope.java From elasticshell with Apache License 2.0 | 6 votes |
/** * Creates a new <code>ShellScope</code> given the actual scope object * @param scope the actual scope object that depends on the engine in use */ ShellScope(Scope scope, ResourceRegistry resourceRegistry) { this.scope = scope; this.resourceRegistry = resourceRegistry; registerJavaClass(Requests.class); registerJavaClass(SearchSourceBuilder.class); registerJavaClass(QueryBuilders.class); registerJavaClass(FilterBuilders.class); registerJavaClass(SortBuilders.class); registerJavaClass(FacetBuilders.class); registerJavaClass(RescoreBuilder.class); registerJavaClass(SuggestBuilder.class); registerJavaClass(AliasAction.class); registerJavaClass(HttpParameters.class); registerJavaClass(AllocateAllocationCommand.class); registerJavaClass(CancelAllocationCommand.class); registerJavaClass(MoveAllocationCommand.class); registerJavaClass(ShardId.class); }
Example #3
Source File: PersonRepositoryTest.java From spring-boot-demo with MIT License | 6 votes |
/** * 自定义高级查询 */ @Test public void customAdvanceSelect() { // 构造查询条件 NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder(); // 添加基本的分词条件 queryBuilder.withQuery(QueryBuilders.matchQuery("remark", "东汉")); // 排序条件 queryBuilder.withSort(SortBuilders.fieldSort("age").order(SortOrder.DESC)); // 分页条件 queryBuilder.withPageable(PageRequest.of(0, 2)); Page<Person> people = repo.search(queryBuilder.build()); log.info("【people】总条数 = {}", people.getTotalElements()); log.info("【people】总页数 = {}", people.getTotalPages()); people.forEach(person -> log.info("【person】= {},年龄 = {}", person.getName(), person.getAge())); }
Example #4
Source File: ByPageTest.java From Spring-Boot-Book with Apache License 2.0 | 6 votes |
@Test /** * Description: 分页查询+排序 */ public void searchByPageAndSort() { // 分页: int page = 0; int size = 5;//每页文档数 // 构建查询条件 NativeSearchQueryBuilder nativeSearchQueryBuilderQueryBuilder = new NativeSearchQueryBuilder(); // 查询词,只能查询一个汉字,或者一个英文单词 nativeSearchQueryBuilderQueryBuilder.withQuery(QueryBuilders.termQuery("name", "富")); // 搜索,获取结果 nativeSearchQueryBuilderQueryBuilder.withSort(SortBuilders.fieldSort("id").order(SortOrder.DESC)); nativeSearchQueryBuilderQueryBuilder.withPageable(PageRequest.of(page, size)); Page<Product> products = productRepository.search(nativeSearchQueryBuilderQueryBuilder.build()); // 总条数 for (Product product : products) { System.out.println(product); } }
Example #5
Source File: PersonRepositoryTest.java From spring-boot-demo with MIT License | 6 votes |
/** * 自定义高级查询 */ @Test public void customAdvanceSelect() { // 构造查询条件 NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder(); // 添加基本的分词条件 queryBuilder.withQuery(QueryBuilders.matchQuery("remark", "东汉")); // 排序条件 queryBuilder.withSort(SortBuilders.fieldSort("age").order(SortOrder.DESC)); // 分页条件 queryBuilder.withPageable(PageRequest.of(0, 2)); Page<Person> people = repo.search(queryBuilder.build()); log.info("【people】总条数 = {}", people.getTotalElements()); log.info("【people】总页数 = {}", people.getTotalPages()); people.forEach(person -> log.info("【person】= {},年龄 = {}", person.getName(), person.getAge())); }
Example #6
Source File: SearchSourceBuilder.java From search-spring-boot-starter with Apache License 2.0 | 6 votes |
public FieldSortBuilder getSort(OrderCondition orderCondition) { final String fieldName = orderCondition.getFieldName(); final SortEnum sort = orderCondition.getOrderCondition(); FieldSortBuilder order; switch (sort) { case ASC: order = SortBuilders.fieldSort(fieldName).order(SortOrder.ASC); break; case DESC: order = SortBuilders.fieldSort(fieldName).order(SortOrder.DESC); break; default: order = null; } return order; }
Example #7
Source File: SearchService.java From leyou with Apache License 2.0 | 6 votes |
/** * 构建基本查询条件 * * @param queryBuilder * @param request */ private void searchWithPageAndSort(NativeSearchQueryBuilder queryBuilder, SearchRequest request) { // 准备分页参数 int page = request.getPage(); int size = request.getSize(); // 1、分页 queryBuilder.withPageable(PageRequest.of(page - 1, size)); // 2、排序 String sortBy = request.getSortBy(); Boolean desc = request.getDescending(); if (StringUtils.isNotBlank(sortBy)) { // 如果不为空,则进行排序 queryBuilder.withSort(SortBuilders.fieldSort(sortBy).order(desc ? SortOrder.DESC : SortOrder.ASC)); } }
Example #8
Source File: SpringDataQueryTest.java From code with Apache License 2.0 | 6 votes |
/** * 排序 */ @Test public void searchAndSort() { // 构建查询条件 NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder(); // 添加基本分词查询 queryBuilder.withQuery(QueryBuilders.termQuery("category", "手机")); // 排序 queryBuilder.withSort(SortBuilders.fieldSort("price").order(SortOrder.ASC)); // 搜索,获取结果 Page<Item> items = itemRepository.search(queryBuilder.build()); // 总条数 long total = items.getTotalElements(); System.out.println("总条数 = " + total); items.forEach(System.out::println); }
Example #9
Source File: ItemServiceImpl.java From poseidon with Apache License 2.0 | 6 votes |
@Override public Page<EsItem> recommend(List<String> itemIds, int page, int size) { Pageable pageable = PageRequest.of(page, size); String[] itemCatNames; if (itemIds.size() != 0) { List<EsItem> esItems = itemRepository.findByItemIdIn(itemIds); itemCatNames = esItems.stream().map(EsItem::getItemCatName).toArray(String[]::new); } else { itemCatNames = new String[] { "手机" }; } System.out.println(Arrays.toString(itemCatNames)); MoreLikeThisQueryBuilder moreLikeThisQueryBuilder = QueryBuilders .moreLikeThisQuery(new String[] { "itemCatName" }, itemCatNames, null).minTermFreq(1); NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder(); nativeSearchQueryBuilder.withQuery(moreLikeThisQueryBuilder).withPageable(pageable) .withSort(SortBuilders.fieldSort("sale").order(SortOrder.DESC)); NativeSearchQuery query = nativeSearchQueryBuilder.build(); // return elasticsearchTemplate.queryForPage(query, EsItem.class); return itemRepository.search(query); }
Example #10
Source File: BaseSearchService.java From albert with MIT License | 6 votes |
protected SortBuilder addSort(SearchParam param){ Integer sort = param.getSort(); // if(null==sort){ // return SortBuilders.fieldSort("lastRefresh").order(SortOrder.DESC); // }else if(Constants.Sort.nearest == sort){ // return SortBuilders.geoDistanceSort("geoPoint").point(param.getLat(), param.getLon()).order(SortOrder.ASC); // // } else if(Constants.Sort.pageView == sort){ // return SortBuilders.fieldSort("reviewNum").order(SortOrder.DESC); // // } else if(Constants.Sort.score == sort){ // return SortBuilders.fieldSort("avgScore").order(SortOrder.DESC); // // } else if(Constants.Sort.priceAsc == sort){ // return SortBuilders.fieldSort("price").order(SortOrder.ASC); // // } else if(Constants.Sort.priceDesc == sort){ // return SortBuilders.fieldSort("price").order(SortOrder.DESC); // // } return SortBuilders.fieldSort("addTime").order(SortOrder.DESC); }
Example #11
Source File: ElasticsearchTransactionRepository.java From servicecomb-pack with Apache License 2.0 | 6 votes |
@Override public List<GlobalTransaction> getSlowGlobalTransactionsTopN(int n) { // ElasticsearchTemplate.prepareScroll() does not add sorting https://jira.spring.io/browse/DATAES-457 ObjectMapper jsonMapper = new ObjectMapper(); List<GlobalTransaction> globalTransactions = new ArrayList(); IndicesStatsResponse indicesStatsResponse = this.template.getClient().admin().indices().prepareStats(INDEX_NAME).get(); if(indicesStatsResponse.getIndices().get(INDEX_NAME).getTotal().docs.getCount()>0){ SearchResponse response = this.template.getClient().prepareSearch(INDEX_NAME) .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setQuery(QueryBuilders.matchAllQuery()) .addSort(SortBuilders.fieldSort("durationTime").order(SortOrder.DESC)) .setFrom(0).setSize(n).setExplain(true) .get(); response.getHits().forEach(hit -> { try { GlobalTransactionDocument dto = jsonMapper .readValue(hit.getSourceAsString(), GlobalTransactionDocument.class); globalTransactions.add(dto); } catch (Exception e) { LOG.error(e.getMessage(), e); } }); } return globalTransactions; }
Example #12
Source File: PersonRepositoryTest.java From spring-boot-demo with MIT License | 6 votes |
/** * 自定义高级查询 */ @Test public void customAdvanceSelect() { // 构造查询条件 NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder(); // 添加基本的分词条件 queryBuilder.withQuery(QueryBuilders.matchQuery("remark", "东汉")); // 排序条件 queryBuilder.withSort(SortBuilders.fieldSort("age").order(SortOrder.DESC)); // 分页条件 queryBuilder.withPageable(PageRequest.of(0, 2)); Page<Person> people = repo.search(queryBuilder.build()); log.info("【people】总条数 = {}", people.getTotalElements()); log.info("【people】总页数 = {}", people.getTotalPages()); people.forEach(person -> log.info("【person】= {},年龄 = {}", person.getName(), person.getAge())); }
Example #13
Source File: ElasticSearchDAOV5.java From conductor with Apache License 2.0 | 6 votes |
@Override public List<Message> getMessages(String queue) { try { Expression expression = Expression.fromString("queue='" + queue + "'"); QueryBuilder queryBuilder = expression.getFilterBuilder(); BoolQueryBuilder filterQuery = QueryBuilders.boolQuery().must(queryBuilder); QueryStringQueryBuilder stringQuery = QueryBuilders.queryStringQuery("*"); BoolQueryBuilder fq = QueryBuilders.boolQuery().must(stringQuery).must(filterQuery); final SearchRequestBuilder srb = elasticSearchClient.prepareSearch(logIndexPrefix + "*") .setQuery(fq) .setTypes(MSG_DOC_TYPE) .addSort(SortBuilders.fieldSort("created").order(SortOrder.ASC)); return mapGetMessagesResponse(srb.execute().actionGet()); } catch (Exception e) { String errorMsg = String.format("Failed to get messages for queue: %s", queue); logger.error(errorMsg, e); throw new ApplicationException(Code.BACKEND_ERROR, errorMsg, e); } }
Example #14
Source File: ElasticSearchDAOV5.java From conductor with Apache License 2.0 | 6 votes |
@Override public List<EventExecution> getEventExecutions(String event) { try { Expression expression = Expression.fromString("event='" + event + "'"); QueryBuilder queryBuilder = expression.getFilterBuilder(); BoolQueryBuilder filterQuery = QueryBuilders.boolQuery().must(queryBuilder); QueryStringQueryBuilder stringQuery = QueryBuilders.queryStringQuery("*"); BoolQueryBuilder fq = QueryBuilders.boolQuery().must(stringQuery).must(filterQuery); final SearchRequestBuilder srb = elasticSearchClient.prepareSearch(logIndexPrefix + "*") .setQuery(fq).setTypes(EVENT_DOC_TYPE) .addSort(SortBuilders.fieldSort("created") .order(SortOrder.ASC)); return mapEventExecutionsResponse(srb.execute().actionGet()); } catch (Exception e) { String errorMsg = String.format("Failed to get executions for event: %s", event); logger.error(errorMsg, e); throw new ApplicationException(Code.BACKEND_ERROR, errorMsg, e); } }
Example #15
Source File: ElasticSearchDAOV6.java From conductor with Apache License 2.0 | 6 votes |
@Override public List<TaskExecLog> getTaskExecutionLogs(String taskId) { try { BoolQueryBuilder query = boolQueryBuilder("taskId='" + taskId + "'", "*"); String docType = StringUtils.isBlank(docTypeOverride) ? LOG_DOC_TYPE : docTypeOverride; final SearchRequestBuilder srb = elasticSearchClient.prepareSearch(logIndexPrefix + "*") .setQuery(query) .setTypes(docType) .setSize(config.getElasticSearchTasklogLimit()) .addSort(SortBuilders.fieldSort("createdTime").order(SortOrder.ASC)); return mapTaskExecLogsResponse(srb.execute().actionGet()); } catch (Exception e) { LOGGER.error("Failed to get task execution logs for task: {}", taskId, e); } return null; }
Example #16
Source File: ElasticSearchDAOV6.java From conductor with Apache License 2.0 | 6 votes |
@Override public List<Message> getMessages(String queue) { try { BoolQueryBuilder fq = boolQueryBuilder("queue='" + queue + "'", "*"); String docType = StringUtils.isBlank(docTypeOverride) ? MSG_DOC_TYPE : docTypeOverride; final SearchRequestBuilder srb = elasticSearchClient.prepareSearch(messageIndexPrefix + "*") .setQuery(fq) .setTypes(docType) .addSort(SortBuilders.fieldSort("created").order(SortOrder.ASC)); return mapGetMessagesResponse(srb.execute().actionGet()); } catch (Exception e) { LOGGER.error("Failed to get messages for queue: {}", queue, e); } return null; }
Example #17
Source File: ElasticSearchDAOV6.java From conductor with Apache License 2.0 | 6 votes |
@Override public List<EventExecution> getEventExecutions(String event) { try { BoolQueryBuilder fq = boolQueryBuilder("event='" + event + "'", "*"); String docType = StringUtils.isBlank(docTypeOverride) ? EVENT_DOC_TYPE : docTypeOverride; final SearchRequestBuilder srb = elasticSearchClient.prepareSearch(eventIndexPrefix + "*") .setQuery(fq).setTypes(docType) .addSort(SortBuilders.fieldSort("created") .order(SortOrder.ASC)); return mapEventExecutionsResponse(srb.execute().actionGet()); } catch (Exception e) { LOGGER.error("Failed to get executions for event: {}", event, e); } return null; }
Example #18
Source File: ESConnector.java From Siamese with GNU General Public License v3.0 | 6 votes |
public long getMaxId(String index, boolean isDFS) throws Exception { SearchType searchType; if (isDFS) searchType = SearchType.DFS_QUERY_THEN_FETCH; else searchType = SearchType.QUERY_THEN_FETCH; SearchResponse response = client.prepareSearch(index).setSearchType(searchType) .addSort(SortBuilders.fieldSort("_score").order(SortOrder.DESC)) .addSort(SortBuilders.fieldSort("file").order(SortOrder.DESC)) .setQuery(QueryBuilders.matchAllQuery()) .addAggregation(AggregationBuilders.max("max_id").field("id")) .execute() .actionGet(); Double maxId = (Double) response.getAggregations().get("max_id").getProperty("value"); return maxId.longValue(); }
Example #19
Source File: ESConnector.java From Siamese with GNU General Public License v3.0 | 6 votes |
public ArrayList<Document> search(String index, String type, String query, boolean isPrint , boolean isDFS, int resultOffset, int resultSize) throws Exception { SearchType searchType; if (isDFS) searchType = SearchType.DFS_QUERY_THEN_FETCH; else searchType = SearchType.QUERY_THEN_FETCH; SearchResponse response = client.prepareSearch(index).setSearchType(searchType) .addSort(SortBuilders.fieldSort("_score").order(SortOrder.DESC)) .addSort(SortBuilders.fieldSort("file").order(SortOrder.DESC)) .setQuery(QueryBuilders.matchQuery("tokenizedsrc", query)) // .setQuery(QueryBuilders.matchQuery("src", query)) .setFrom(resultOffset).setSize(resultSize).execute() .actionGet(); SearchHit[] hits = response.getHits().getHits(); return prepareResults(hits, resultSize, isPrint); }
Example #20
Source File: EsSort.java From es-service-parent with Apache License 2.0 | 6 votes |
/** * * @param sort_fileds * @return */ public static List<SortBuilder> sortAdapter(List<String> sort_fileds) { List<SortBuilder> sortBuilders = new ArrayList<SortBuilder>(); for (String sort : sort_fileds) { String[] items = StringUtils.split(sort, " "); if (items.length > 2 || items.length < 2) { throw new RuntimeException("排序参数格式不正确,必须为:filed desc|asc,多个filed以逗号分隔!"); } String[] fileds = items[0].split(","); for (String filed : fileds) { SortBuilder sortb = null; if (items[0].equalsIgnoreCase("desc")) { sortb = SortBuilders.fieldSort(filed).order(SortOrder.DESC); } else { sortb = SortBuilders.fieldSort(filed).order(SortOrder.ASC); } sortBuilders.add(sortb); } } return sortBuilders; }
Example #21
Source File: ElasticSearchIntegrationTest.java From core-ng-project with Apache License 2.0 | 6 votes |
@Test void search() { TestDocument document = document("1", "1st Test's Product", 1, 0, null, LocalTime.NOON); documentType.index(document.id, document); elasticSearch.refreshIndex("document"); // test synonyms SearchRequest request = new SearchRequest(); request.query = boolQuery() .must(matchQuery("string_field", "first")) .filter(termQuery("enum_field", JSON.toEnumValue(TestDocument.TestEnum.VALUE1))); request.sorts.add(SortBuilders.scriptSort(new Script("doc['int_field'].value * 3"), ScriptSortBuilder.ScriptSortType.NUMBER)); SearchResponse<TestDocument> response = documentType.search(request); assertThat(response.totalHits).isEqualTo(1); assertThat(response.hits.get(0)).isEqualToIgnoringGivenFields(document, "zonedDateTimeField"); // test stemmer request = new SearchRequest(); request.query = matchQuery("string_field", "test"); response = documentType.search(request); assertThat(response.totalHits).isEqualTo(1); assertThat(response.hits.get(0)).isEqualToIgnoringGivenFields(document, "zonedDateTimeField"); }
Example #22
Source File: DefaultQueryAction.java From elasticsearch-sql with Apache License 2.0 | 6 votes |
/** * Add sorts to the elasticsearch query based on the 'ORDER BY' clause. * * @param orderBys * list of Order object */ private void setSorts(List<Order> orderBys) { for (Order order : orderBys) { if (order.getNestedPath() != null) { request.addSort(SortBuilders.fieldSort(order.getName()).order(SortOrder.valueOf(order.getType())).setNestedSort(new NestedSortBuilder(order.getNestedPath()))); } else if (order.getName().contains("script(")) { //zhongshu-comment 该分支是我后来加的,用于兼容order by case when那种情况 String scriptStr = order.getName().substring("script(".length(), order.getName().length() - 1); Script script = new Script(scriptStr); ScriptSortBuilder scriptSortBuilder = SortBuilders.scriptSort(script, order.getScriptSortType()); scriptSortBuilder = scriptSortBuilder.order(SortOrder.valueOf(order.getType())); request.addSort(scriptSortBuilder); } else { request.addSort( order.getName(), SortOrder.valueOf(order.getType())); } } }
Example #23
Source File: GitHubRiver.java From elasticsearch-river-github with Apache License 2.0 | 6 votes |
/** * 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; } }
Example #24
Source File: ElasticsearchConsolePersistence.java From foxtrot with Apache License 2.0 | 6 votes |
@Override public List<ConsoleV2> getAllOldVersions(final String name, final String sortBy) { try { SearchHits searchHits = connection.getClient() .prepareSearch(INDEX_HISTORY) .setSearchType(SearchType.QUERY_THEN_FETCH) .setQuery(QueryBuilders.termQuery("name.keyword", name)) .addSort(SortBuilders.fieldSort(sortBy) .order(SortOrder.DESC)) .setFrom(0) .setSize(10) .execute() .actionGet() .getHits(); List<ConsoleV2> results = new ArrayList<>(); for (SearchHit searchHit : CollectionUtils.nullAndEmptySafeValueList(searchHits.getHits())) { results.add(mapper.readValue(searchHit.getSourceAsString(), ConsoleV2.class)); } return results; } catch (Exception e) { throw new ConsoleFetchException(e); } }
Example #25
Source File: ConsoleHistoryManager.java From foxtrot with Apache License 2.0 | 6 votes |
private void deleteOldData(final String name) { String updatedAt = "updatedAt"; try { SearchHits searchHits = connection.getClient() .prepareSearch(INDEX_HISTORY) .setTypes(TYPE) .setSearchType(SearchType.QUERY_THEN_FETCH) .setQuery(QueryBuilders.termQuery("name.keyword", name)) .addSort(SortBuilders.fieldSort(updatedAt) .order(SortOrder.DESC)) .setFrom(10) .setSize(9000) .execute() .actionGet() .getHits(); for(SearchHit searchHit : CollectionUtils.nullAndEmptySafeValueList(searchHits.getHits())) { ConsoleV2 consoleV2 = mapper.readValue(searchHit.getSourceAsString(), ConsoleV2.class); elasticsearchConsolePersistence.deleteOldVersion(consoleV2.getId()); } } catch (Exception e) { throw new ConsoleFetchException(e); } }
Example #26
Source File: BaseClient.java From elasticsearch-helper with Apache License 2.0 | 6 votes |
public Long mostRecentDocument(String index) { if (client() == null) { return null; } SearchRequestBuilder searchRequestBuilder = new SearchRequestBuilder(client(), SearchAction.INSTANCE); SortBuilder sort = SortBuilders.fieldSort("_timestamp").order(SortOrder.DESC); SearchResponse searchResponse = searchRequestBuilder.setIndices(index).addField("_timestamp").setSize(1).addSort(sort).execute().actionGet(); if (searchResponse.getHits().getHits().length == 1) { SearchHit hit = searchResponse.getHits().getHits()[0]; if (hit.getFields().get("_timestamp") != null) { return hit.getFields().get("_timestamp").getValue(); } else { return 0L; } } return null; }
Example #27
Source File: SearchRequestBuilderStrategy.java From usergrid with Apache License 2.0 | 6 votes |
/** * Apply our default sort predicate logic */ private void applyDefaultSortPredicates( final SearchRequestBuilder srb, final GeoSortFields geoFields ) { //we have geo fields, sort through them in visit order for ( String geoField : geoFields.fields() ) { final GeoDistanceSortBuilder geoSort = geoFields.applyOrder( geoField, SortOrder.ASC ); srb.addSort( geoSort ); } //now sort by edge timestamp, then entity id //sort by the edge timestamp srb.addSort( SortBuilders.fieldSort( IndexingUtils.EDGE_TIMESTAMP_FIELDNAME ).order( SortOrder.DESC ) ); // removing secondary sort by entity ID -- takes ES resources and provides no benefit //sort by the entity id if our times are equal //srb.addSort( SortBuilders.fieldSort( IndexingUtils.ENTITY_ID_FIELDNAME ).order( SortOrder.ASC ) ); return; }
Example #28
Source File: ByPageTest.java From Spring-Boot-Book with Apache License 2.0 | 6 votes |
@Test /** * Description: 分页查询+排序 */ public void searchByPageAndSort() { // 分页: int page = 0; int size = 5;//每页文档数 // 构建查询条件 NativeSearchQueryBuilder nativeSearchQueryBuilderQueryBuilder = new NativeSearchQueryBuilder(); // 查询词,只能查询一个汉字,或者一个英文单词 nativeSearchQueryBuilderQueryBuilder.withQuery(QueryBuilders.termQuery("name", "富")); // 搜索,获取结果 nativeSearchQueryBuilderQueryBuilder.withSort(SortBuilders.fieldSort("id").order(SortOrder.DESC)); nativeSearchQueryBuilderQueryBuilder.withPageable(PageRequest.of(page, size)); Page<Product> products = productRepository.search(nativeSearchQueryBuilderQueryBuilder.build()); // 总条数 for (Product product : products) { System.out.println(product); } }
Example #29
Source File: ItemServiceImpl.java From poseidon with Apache License 2.0 | 5 votes |
@Override public Page<EsItem> getByKey(String keyWord, int page, int limit) { Pageable pageable = PageRequest.of(page, limit); QueryBuilder queryBuilder = QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("name", keyWord)) .should(QueryBuilders.matchQuery("sellPoint", keyWord)); NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder(); nativeSearchQueryBuilder.withQuery(queryBuilder).withPageable(pageable) .withSort(SortBuilders.fieldSort("sale").order(SortOrder.DESC)); NativeSearchQuery query = nativeSearchQueryBuilder.build(); LOGGER.info("DSL:{}", query.getQuery().toString()); return elasticsearchTemplate.queryForPage(query, EsItem.class); }
Example #30
Source File: SortConverter.java From james-project with Apache License 2.0 | 5 votes |
private static FieldSortBuilder getSortClause(SearchQuery.Sort.SortClause clause) { switch (clause) { case Arrival : return SortBuilders.fieldSort(JsonMessageConstants.DATE); case MailboxCc : return SortBuilders.fieldSort(JsonMessageConstants.CC + PATH_SEPARATOR + JsonMessageConstants.EMailer.ADDRESS + PATH_SEPARATOR + NodeMappingFactory.RAW).setNestedSort(new NestedSortBuilder(JsonMessageConstants.CC)); case MailboxFrom : return SortBuilders.fieldSort(JsonMessageConstants.FROM + PATH_SEPARATOR + JsonMessageConstants.EMailer.ADDRESS + PATH_SEPARATOR + NodeMappingFactory.RAW).setNestedSort(new NestedSortBuilder(JsonMessageConstants.FROM)); case MailboxTo : return SortBuilders.fieldSort(JsonMessageConstants.TO + PATH_SEPARATOR + JsonMessageConstants.EMailer.ADDRESS + PATH_SEPARATOR + NodeMappingFactory.RAW).setNestedSort(new NestedSortBuilder(JsonMessageConstants.TO)); case BaseSubject : return SortBuilders.fieldSort(JsonMessageConstants.SUBJECT + PATH_SEPARATOR + NodeMappingFactory.RAW); case Size : return SortBuilders.fieldSort(JsonMessageConstants.SIZE); case SentDate : return SortBuilders.fieldSort(JsonMessageConstants.SENT_DATE); case Uid : return SortBuilders.fieldSort(JsonMessageConstants.UID); case DisplayFrom: return SortBuilders.fieldSort(JsonMessageConstants.FROM + PATH_SEPARATOR + JsonMessageConstants.EMailer.NAME + PATH_SEPARATOR + NodeMappingFactory.RAW).setNestedSort(new NestedSortBuilder(JsonMessageConstants.FROM)); case DisplayTo: return SortBuilders.fieldSort(JsonMessageConstants.TO + PATH_SEPARATOR + JsonMessageConstants.EMailer.NAME + PATH_SEPARATOR + NodeMappingFactory.RAW).setNestedSort(new NestedSortBuilder(JsonMessageConstants.TO)); case Id: return SortBuilders.fieldSort(JsonMessageConstants.MESSAGE_ID); default: throw new RuntimeException("Sort is not implemented"); } }