org.elasticsearch.search.sort.FieldSortBuilder Java Examples

The following examples show how to use org.elasticsearch.search.sort.FieldSortBuilder. 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: QuickReplyRepositoryImpl.java    From youkefu with Apache License 2.0 8 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public Page<QuickReply> getByCon(BoolQueryBuilder boolQueryBuilder, final int p , final int ps) {

	Page<QuickReply> pages  = null ;
	
	QueryBuilder beginFilter = QueryBuilders.boolQuery().should(QueryBuilders.missingQuery("begintime")).should(QueryBuilders.rangeQuery("begintime").from(new Date().getTime())) ;
	QueryBuilder endFilter = QueryBuilders.boolQuery().should(QueryBuilders.missingQuery("endtime")).should(QueryBuilders.rangeQuery("endtime").to(new Date().getTime())) ;
	
    NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withFilter(QueryBuilders.boolQuery().must(beginFilter).must(endFilter)).withSort(new FieldSortBuilder("createtime").unmappedType("date").order(SortOrder.DESC));
    
    SearchQuery searchQuery = searchQueryBuilder.build().setPageable(new PageRequest(p, ps)) ;
    if(elasticsearchTemplate.indexExists(QuickReply.class)){
    	pages = elasticsearchTemplate.queryForPage(searchQuery, QuickReply.class);
    }
    return pages ; 
}
 
Example #2
Source File: QuickReplyRepositoryImpl.java    From youkefu with Apache License 2.0 7 votes vote down vote up
@Override
public List<QuickReply> getQuickReplyByOrgi(String orgi , String cate,String type, String q) {
	
	List<QuickReply> list  = null ;
	
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	boolQueryBuilder.must(termQuery("orgi" , orgi)) ;
	
	if(!StringUtils.isBlank(cate)){
		boolQueryBuilder.must(termQuery("cate" , cate)) ;
	}
	if(!StringUtils.isBlank(type)){
		boolQueryBuilder.must(termQuery("type" , type)) ;
	}
    if(!StringUtils.isBlank(q)){
    	boolQueryBuilder.must(new QueryStringQueryBuilder(q).defaultOperator(Operator.AND)) ;
    }
	
	NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withSort(new FieldSortBuilder("top").unmappedType("boolean").order(SortOrder.DESC)).withSort(new FieldSortBuilder("updatetime").unmappedType("date").order(SortOrder.DESC));
	SearchQuery searchQuery = searchQueryBuilder.build().setPageable(new PageRequest(0, 10000));
	if(elasticsearchTemplate.indexExists(QuickReply.class)){
		list = elasticsearchTemplate.queryForList(searchQuery, QuickReply.class);
    }
    return list ; 
}
 
Example #3
Source File: ElasticSearchRestDAOV6.java    From conductor with Apache License 2.0 6 votes vote down vote up
@Override
public List<EventExecution> getEventExecutions(String event) {
    try {
        BoolQueryBuilder query = boolQueryBuilder("event='" + event + "'", "*");

        // Create the searchObjectIdsViaExpression source
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(query);
        searchSourceBuilder.sort(new FieldSortBuilder("created").order(SortOrder.ASC));

        // Generate the actual request to send to ES.
        String docType = StringUtils.isBlank(docTypeOverride) ? EVENT_DOC_TYPE : docTypeOverride;
        SearchRequest searchRequest = new SearchRequest(eventIndexPrefix + "*");
        searchRequest.types(docType);
        searchRequest.source(searchSourceBuilder);

        SearchResponse response = elasticSearchClient.search(searchRequest);

        return mapEventExecutionsResponse(response);
    } catch (Exception e) {
        logger.error("Failed to get executions for event: {}", event, e);
    }
    return null;
}
 
Example #4
Source File: ElasticSearchRestDAOV6.java    From conductor with Apache License 2.0 6 votes vote down vote up
@Override
public List<TaskExecLog> getTaskExecutionLogs(String taskId) {
    try {
        BoolQueryBuilder query = boolQueryBuilder("taskId='" + taskId + "'", "*");

        // Create the searchObjectIdsViaExpression source
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(query);
        searchSourceBuilder.sort(new FieldSortBuilder("createdTime").order(SortOrder.ASC));
        searchSourceBuilder.size(config.getElasticSearchTasklogLimit());

        // Generate the actual request to send to ES.
        String docType = StringUtils.isBlank(docTypeOverride) ? LOG_DOC_TYPE : docTypeOverride;
        SearchRequest searchRequest = new SearchRequest(logIndexPrefix + "*");
        searchRequest.types(docType);
        searchRequest.source(searchSourceBuilder);

        SearchResponse response = elasticSearchClient.search(searchRequest);

        return mapTaskExecLogsResponse(response);
    } catch (Exception e) {
        logger.error("Failed to get task execution logs for task: {}", taskId, e);
    }
    return null;
}
 
Example #5
Source File: GitHubRiver.java    From elasticsearch-river-github with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #6
Source File: QuickReplyRepositoryImpl.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@Override
public Page<QuickReply> getByOrgiAndCate(String orgi ,String cate , String q, Pageable page) {

	Page<QuickReply> pages  = null ;
	
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	boolQueryBuilder.must(termQuery("cate" , cate)) ;
	
    if(!StringUtils.isBlank(q)){
    	boolQueryBuilder.must(new QueryStringQueryBuilder(q).defaultOperator(Operator.AND)) ;
    }
    NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withSort(new FieldSortBuilder("createtime").unmappedType("date").order(SortOrder.DESC));
    searchQueryBuilder.withHighlightFields(new HighlightBuilder.Field("title").fragmentSize(200)) ;
    SearchQuery searchQuery = searchQueryBuilder.build().setPageable(page) ;
    if(elasticsearchTemplate.indexExists(QuickReply.class)){
    	pages = elasticsearchTemplate.queryForPage(searchQuery, QuickReply.class , new UKResultMapper());
    }
    return pages ; 
}
 
Example #7
Source File: SlowOperQueryHandler.java    From uavstack with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #8
Source File: TopicRepositoryImpl.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@Override
public List<Topic> getTopicByOrgi(String orgi , String type, String q) {
	
	List<Topic> list  = null ;
	
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	boolQueryBuilder.must(termQuery("orgi" , orgi)) ;
	
	if(!StringUtils.isBlank(type)){
		boolQueryBuilder.must(termQuery("cate" , type)) ;
	}
	
    if(!StringUtils.isBlank(q)){
    	boolQueryBuilder.must(new QueryStringQueryBuilder(q).defaultOperator(Operator.AND)) ;
    }
	
	NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withSort(new FieldSortBuilder("top").unmappedType("boolean").order(SortOrder.DESC)).withSort(new FieldSortBuilder("updatetime").unmappedType("date").order(SortOrder.DESC));
	SearchQuery searchQuery = searchQueryBuilder.build();
	if(elasticsearchTemplate.indexExists(Topic.class)){
		list = elasticsearchTemplate.queryForList(searchQuery, Topic.class);
    }
    return list ; 
}
 
Example #9
Source File: TopicRepositoryImpl.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public Page<Topic> getTopicByCon(BoolQueryBuilder boolQueryBuilder, final int p , final int ps) {

	Page<Topic> pages  = null ;
	
	QueryBuilder beginFilter = QueryBuilders.boolQuery().should(QueryBuilders.missingQuery("begintime")).should(QueryBuilders.rangeQuery("begintime").to(new Date().getTime())) ;
	QueryBuilder endFilter = QueryBuilders.boolQuery().should(QueryBuilders.missingQuery("endtime")).should(QueryBuilders.rangeQuery("endtime").from(new Date().getTime())) ;
	
    NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withFilter(QueryBuilders.boolQuery().must(beginFilter).must(endFilter)).withSort(new FieldSortBuilder("createtime").unmappedType("date").order(SortOrder.DESC));
    SearchQuery searchQuery = searchQueryBuilder.build().setPageable(new PageRequest(p, ps)) ;
    if(elasticsearchTemplate.indexExists(Topic.class)){
    	pages = elasticsearchTemplate.queryForPage(searchQuery, Topic.class);
    }
    return pages ; 
}
 
Example #10
Source File: TopicRepositoryImpl.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@Override
public Page<Topic> getTopicByCateAndUser(String cate  , String q , String user ,final int p , final int ps) {

	Page<Topic> pages  = null ;
	
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	boolQueryBuilder.must(termQuery("cate" , cate)) ;
	
    if(!StringUtils.isBlank(q)){
    	boolQueryBuilder.must(new QueryStringQueryBuilder(q).defaultOperator(Operator.AND)) ;
    }
	
	NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withQuery(termQuery("creater" , user)).withSort(new FieldSortBuilder("top").unmappedType("boolean").order(SortOrder.DESC)).withSort(new FieldSortBuilder("updatetime").unmappedType("date").order(SortOrder.DESC));
	SearchQuery searchQuery = searchQueryBuilder.build().setPageable(new PageRequest(p, ps));
	if(elasticsearchTemplate.indexExists(Topic.class)){
		pages = elasticsearchTemplate.queryForPage(searchQuery, Topic.class, new XiaoEUKResultMapper());
    }
    return pages ; 
}
 
Example #11
Source File: TopicRepositoryImpl.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public Page<Topic> getTopicByTopAndOrgi(boolean top ,String orgi, String aiid ,final int p , final int ps) {

	Page<Topic> pages  = null ;
	
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	boolQueryBuilder.must(termQuery("top" , top)) ;
	boolQueryBuilder.must(termQuery("orgi" , orgi)) ;
	if(!StringUtils.isBlank(aiid)) {
		boolQueryBuilder.must(termQuery("aiid" , aiid)) ;
	}
	
	QueryBuilder beginFilter = QueryBuilders.boolQuery().should(QueryBuilders.missingQuery("begintime")).should(QueryBuilders.rangeQuery("begintime").to(new Date().getTime())) ;
	QueryBuilder endFilter = QueryBuilders.boolQuery().should(QueryBuilders.missingQuery("endtime")).should(QueryBuilders.rangeQuery("endtime").from(new Date().getTime())) ;
	
    NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withFilter(QueryBuilders.boolQuery().must(beginFilter).must(endFilter)).withSort(new FieldSortBuilder("createtime").unmappedType("date").order(SortOrder.DESC));
    
   
    searchQueryBuilder.withHighlightFields(new HighlightBuilder.Field("title").fragmentSize(200)) ;
    SearchQuery searchQuery = searchQueryBuilder.build().setPageable(new PageRequest(p, ps)) ;
    if(elasticsearchTemplate.indexExists(Topic.class)){
    	pages = elasticsearchTemplate.queryForPage(searchQuery, Topic.class , new XiaoEUKResultMapper());
    }
    return pages ; 
}
 
Example #12
Source File: TopicRepositoryImpl.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@Override
public Page<Topic> getTopicByCateAndOrgi(String cate ,String orgi, String q, final int p , final int ps) {

	Page<Topic> pages  = null ;
	
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	if(!StringUtils.isBlank(cate)) {
		boolQueryBuilder.must(termQuery("cate" , cate)) ;
	}
	boolQueryBuilder.must(termQuery("orgi" , orgi)) ;
    if(!StringUtils.isBlank(q)){
    	boolQueryBuilder.must(new QueryStringQueryBuilder(q).defaultOperator(Operator.AND)) ;
    }
    NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withSort(new FieldSortBuilder("top").unmappedType("boolean").order(SortOrder.DESC)).withSort(new FieldSortBuilder("createtime").unmappedType("date").order(SortOrder.DESC));
    searchQueryBuilder.withHighlightFields(new HighlightBuilder.Field("title").fragmentSize(200)) ;
    SearchQuery searchQuery = searchQueryBuilder.build().setPageable(new PageRequest(p, ps)) ;
    if(elasticsearchTemplate.indexExists(Topic.class)){
    	pages = elasticsearchTemplate.queryForPage(searchQuery, Topic.class , new XiaoEUKResultMapper());
    }
    return pages ; 
}
 
Example #13
Source File: EkmKnowledgeMasterRepositoryImpl.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
private Page<EkmKnowledgeMaster> processQueryItem(BoolQueryBuilder boolQueryBuilder, Pageable page){
	
	//过滤掉已过期的知识
	//QueryBuilder beginFilter = QueryBuilders.boolQuery().should(QueryBuilders.missingQuery("begintime")).should(QueryBuilders.rangeQuery("begintime").to(new Date().getTime())) ;
	//QueryBuilder endFilter = QueryBuilders.boolQuery().should(QueryBuilders.missingQuery("endtime")).should(QueryBuilders.rangeQuery("endtime").from(new Date().getTime())) ;
	
	NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withSort(new FieldSortBuilder("createtime").unmappedType("date").order(SortOrder.DESC));
	searchQueryBuilder.withHighlightFields(new Field("title") , new Field("content")) ;
	
	searchQueryBuilder.withPageable(page) ;
	
	Page<EkmKnowledgeMaster> knowledgeList = null ;
	if(elasticsearchTemplate.indexExists(EkmKnowledgeMaster.class)){
		knowledgeList = elasticsearchTemplate.queryForPage(searchQueryBuilder.build() , EkmKnowledgeMaster.class , new EKMResultMapper()) ;
	}
	
	return knowledgeList;
}
 
Example #14
Source File: EkmKnowledgeMasterRepositoryImpl.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
private Page<EkmKnowledgeMaster> processQuery(BoolQueryBuilder boolQueryBuilder, Pageable page){
	
	//过滤掉已过期的知识
	QueryBuilder beginFilter = QueryBuilders.boolQuery().should(QueryBuilders.missingQuery("begintime")).should(QueryBuilders.rangeQuery("begintime").to(new Date().getTime())) ;
	QueryBuilder endFilter = QueryBuilders.boolQuery().should(QueryBuilders.missingQuery("endtime")).should(QueryBuilders.rangeQuery("endtime").from(new Date().getTime())) ;
	
	NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withFilter(QueryBuilders.boolQuery().must(beginFilter).must(endFilter)).withSort(new FieldSortBuilder("createtime").unmappedType("date").order(SortOrder.DESC));
	searchQueryBuilder.withHighlightFields(new Field("title") , new Field("content")) ;
	
	searchQueryBuilder.withPageable(page) ;
	
	Page<EkmKnowledgeMaster> knowledgeList = null ;
	if(elasticsearchTemplate.indexExists(EkmKnowledgeMaster.class)){
		knowledgeList = elasticsearchTemplate.queryForPage(searchQueryBuilder.build() , EkmKnowledgeMaster.class , new EKMResultMapper()) ;
	}
	
	return knowledgeList;
}
 
Example #15
Source File: QuickReplyRepositoryImpl.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@Override
public Page<QuickReply> getByQuicktype(String quicktype , final int p , final int ps) {

	Page<QuickReply> pages  = null ;
	
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	boolQueryBuilder.must(termQuery("type" , quicktype)) ;
	
    NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withSort(new FieldSortBuilder("createtime").unmappedType("date").order(SortOrder.DESC));
    
    searchQueryBuilder.withHighlightFields(new HighlightBuilder.Field("title").fragmentSize(200)) ;
    SearchQuery searchQuery = searchQueryBuilder.build().setPageable(new PageRequest(p, ps)) ;
    if(elasticsearchTemplate.indexExists(QuickReply.class)){
    	pages = elasticsearchTemplate.queryForPage(searchQuery, QuickReply.class , new UKResultMapper());
    }
    return pages ; 
}
 
Example #16
Source File: QuickReplyRepositoryImpl.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@Override
public Page<QuickReply> getByOrgiAndType(String orgi ,String type, String q , Pageable page) {
	
	Page<QuickReply> list  = null ;
	
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	boolQueryBuilder.must(termQuery("orgi" , orgi)) ;
	if(!StringUtils.isBlank(type)) {
		boolQueryBuilder.must(termQuery("type" , type)) ;
	}
	
    if(!StringUtils.isBlank(q)){
    	boolQueryBuilder.must(new QueryStringQueryBuilder(q).defaultOperator(Operator.AND)) ;
    }
	
	NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withSort(new FieldSortBuilder("createtime").unmappedType("date").order(SortOrder.DESC));
	SearchQuery searchQuery = searchQueryBuilder.build().setPageable(page);
	if(elasticsearchTemplate.indexExists(QuickReply.class)){
		list = elasticsearchTemplate.queryForPage(searchQuery, QuickReply.class);
    }
    return list ; 
}
 
Example #17
Source File: EkmKnowledgeCollectRepositoryImpl.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@Override
public Page<EkmKnowledgeCollect> findByCreaterAndStatusAndOrgi(BoolQueryBuilder boolQuery,
		String creater, String status, String orgi, Pageable pageable) {
	HasParentQueryBuilder hasParentQueryBuilder=QueryBuilders.hasParentQuery("uk_ekm_kb_master",QueryBuilders.termQuery("datastatus", false));
	boolQuery.must(hasParentQueryBuilder) ;
	boolQuery.must(QueryBuilders.termQuery("status", status)) ;
	boolQuery.must(QueryBuilders.termQuery("creater", creater)) ;
	boolQuery.must(QueryBuilders.termQuery("orgi", orgi)) ;
	NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQuery).withSort(new FieldSortBuilder("createtime").unmappedType("date").order(SortOrder.DESC));
	searchQueryBuilder.withPageable(pageable) ;
	Page<EkmKnowledgeCollect> knowledgeCollectList = null ;
	if(elasticsearchTemplate.indexExists(EkmKnowledgeTimes.class)){
		knowledgeCollectList = elasticsearchTemplate.queryForPage(searchQueryBuilder.build() , EkmKnowledgeCollect.class ) ;
    }
	
	return knowledgeCollectList;
}
 
Example #18
Source File: KbsTopicRepositoryImpl.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@Override
public Page<KbsTopic> getTopicByCate(String cate , String q, final int p , final int ps) {

	Page<KbsTopic> pages  = null ;
	
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	boolQueryBuilder.must(termQuery("cate" , cate)) ;
	
    if(!StringUtils.isBlank(q)){
    	boolQueryBuilder.must(new QueryStringQueryBuilder(q).defaultOperator(Operator.AND)) ;
    }
    NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withSort(new FieldSortBuilder("createtime").unmappedType("date").order(SortOrder.DESC));
    searchQueryBuilder.withHighlightFields(new HighlightBuilder.Field("title").fragmentSize(200)) ;
    SearchQuery searchQuery = searchQueryBuilder.build().setPageable(new PageRequest(p, ps)) ;
    if(elasticsearchTemplate.indexExists(KbsTopic.class)){
    	pages = elasticsearchTemplate.queryForPage(searchQuery, KbsTopic.class , new UKResultMapper());
    }
    return pages ; 
}
 
Example #19
Source File: KbsTopicRepositoryImpl.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public Page<KbsTopic> getTopicByTop(boolean top , final int p , final int ps) {

	Page<KbsTopic> pages  = null ;
	
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	boolQueryBuilder.must(termQuery("top" , top)) ;
	
	QueryBuilder beginFilter = QueryBuilders.boolQuery().should(QueryBuilders.missingQuery("begintime")).should(QueryBuilders.rangeQuery("begintime").from(new Date().getTime())) ;
	QueryBuilder endFilter = QueryBuilders.boolQuery().should(QueryBuilders.missingQuery("endtime")).should(QueryBuilders.rangeQuery("endtime").to(new Date().getTime())) ;
	
    NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withFilter(QueryBuilders.boolQuery().must(beginFilter).must(endFilter)).withSort(new FieldSortBuilder("createtime").unmappedType("date").order(SortOrder.DESC));
    
    searchQueryBuilder.withHighlightFields(new HighlightBuilder.Field("title").fragmentSize(200)) ;
    SearchQuery searchQuery = searchQueryBuilder.build().setPageable(new PageRequest(p, ps)) ;
    if(elasticsearchTemplate.indexExists(KbsTopic.class)){
    	pages = elasticsearchTemplate.queryForPage(searchQuery, KbsTopic.class , new UKResultMapper());
    }
    return pages ; 
}
 
Example #20
Source File: KbsTopicRepositoryImpl.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@Override
public Page<KbsTopic> getTopicByCateAndUser(String cate  , String q , String user ,final int p , final int ps) {

	Page<KbsTopic> pages  = null ;
	
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	boolQueryBuilder.must(termQuery("cate" , cate)) ;
	
    if(!StringUtils.isBlank(q)){
    	boolQueryBuilder.must(new QueryStringQueryBuilder(q).defaultOperator(Operator.AND)) ;
    }
	
	NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withQuery(termQuery("creater" , user)).withSort(new FieldSortBuilder("top").unmappedType("boolean").order(SortOrder.DESC)).withSort(new FieldSortBuilder("updatetime").unmappedType("date").order(SortOrder.DESC));
	SearchQuery searchQuery = searchQueryBuilder.build().setPageable(new PageRequest(p, ps));
	if(elasticsearchTemplate.indexExists(KbsTopic.class)){
		pages = elasticsearchTemplate.queryForPage(searchQuery, KbsTopic.class, new UKResultMapper());
    }
    return pages ; 
}
 
Example #21
Source File: KbsTopicRepositoryImpl.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public Page<KbsTopic> getTopicByCon(BoolQueryBuilder boolQueryBuilder, final int p , final int ps) {

	Page<KbsTopic> pages  = null ;
	
	QueryBuilder beginFilter = QueryBuilders.boolQuery().should(QueryBuilders.missingQuery("begintime")).should(QueryBuilders.rangeQuery("begintime").from(new Date().getTime())) ;
	QueryBuilder endFilter = QueryBuilders.boolQuery().should(QueryBuilders.missingQuery("endtime")).should(QueryBuilders.rangeQuery("endtime").to(new Date().getTime())) ;
	
    NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withFilter(QueryBuilders.boolQuery().must(beginFilter).must(endFilter)).withSort(new FieldSortBuilder("createtime").unmappedType("date").order(SortOrder.DESC));
    
    SearchQuery searchQuery = searchQueryBuilder.build().setPageable(new PageRequest(p, ps)) ;
    if(elasticsearchTemplate.indexExists(KbsTopic.class)){
    	pages = elasticsearchTemplate.queryForPage(searchQuery, KbsTopic.class);
    }
    return pages ; 
}
 
Example #22
Source File: KbsTopicRepositoryImpl.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@Override
public List<KbsTopic> getTopicByOrgi(String orgi , String type, String q) {
	
	List<KbsTopic> list  = null ;
	
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	boolQueryBuilder.must(termQuery("orgi" , orgi)) ;
	
	if(!StringUtils.isBlank(type)){
		boolQueryBuilder.must(termQuery("cate" , type)) ;
	}
	
    if(!StringUtils.isBlank(q)){
    	boolQueryBuilder.must(new QueryStringQueryBuilder(q).defaultOperator(Operator.AND)) ;
    }
	
	NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withSort(new FieldSortBuilder("top").unmappedType("boolean").order(SortOrder.DESC)).withSort(new FieldSortBuilder("updatetime").unmappedType("date").order(SortOrder.DESC));
	SearchQuery searchQuery = searchQueryBuilder.build();
	if(elasticsearchTemplate.indexExists(KbsTopic.class)){
		list = elasticsearchTemplate.queryForList(searchQuery, KbsTopic.class);
    }
    return list ; 
}
 
Example #23
Source File: EkmKnowledgeTimesRepositoryImpl.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@Override
public Page<EkmKnowledgeTimes> findByOrgi(String orgi, Pageable pageable) {
	
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	
	boolQueryBuilder.must(QueryBuilders.termQuery("orgi", orgi)) ;
	HasParentQueryBuilder hasParentQueryBuilder=QueryBuilders.hasParentQuery("uk_ekm_kb_master",QueryBuilders.termQuery("datastatus", false));
	NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withSort(new FieldSortBuilder("viewtimes").unmappedType("long").order(SortOrder.DESC)).withQuery(hasParentQueryBuilder);
	searchQueryBuilder.withPageable(pageable) ;
	Page<EkmKnowledgeTimes> knowledgeTimesList = null ;
	if(elasticsearchTemplate.indexExists(EkmKnowledgeTimes.class)){
		knowledgeTimesList = elasticsearchTemplate.queryForPage(searchQueryBuilder.build() , EkmKnowledgeTimes.class ) ;
    }
	
	return knowledgeTimesList;
}
 
Example #24
Source File: SearchSourceBuilder.java    From search-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
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 #25
Source File: AnomalyDetectorProfileRunner.java    From anomaly-detection with Apache License 2.0 6 votes vote down vote up
/**
 * Create search request to get the latest anomaly result after AD job enabled time
 * @param detectorId detector id
 * @param enabledTime the time when AD job is enabled in milliseconds
 * @return the search request
 */
private SearchRequest createLatestAnomalyResultRequest(String detectorId, long enabledTime, long disabledTime, String[] index) {
    BoolQueryBuilder filterQuery = new BoolQueryBuilder();
    filterQuery.filter(QueryBuilders.termQuery(AnomalyResult.DETECTOR_ID_FIELD, detectorId));
    RangeQueryBuilder rangeBuilder = QueryBuilders.rangeQuery(AnomalyResult.EXECUTION_END_TIME_FIELD).gte(enabledTime);
    if (disabledTime >= enabledTime) {
        rangeBuilder.lte(disabledTime);
    }
    filterQuery.filter(rangeBuilder);

    FieldSortBuilder sortQuery = new FieldSortBuilder(AnomalyResult.EXECUTION_END_TIME_FIELD).order(SortOrder.DESC);

    // I am only looking for last 1 occurrence and have no interest in the total number of documents that match the query.
    // ES will not try to count the number of documents and will be able to terminate the query as soon as 1 document
    // have been collected per segment.
    SearchSourceBuilder source = new SearchSourceBuilder().query(filterQuery).size(1).sort(sortQuery).trackTotalHits(false);

    SearchRequest request = new SearchRequest(index);
    request.source(source);
    return request;
}
 
Example #26
Source File: ElasticSearchRestDAOV6.java    From conductor with Apache License 2.0 6 votes vote down vote up
@Override
public List<Message> getMessages(String queue) {
    try {
        BoolQueryBuilder query = boolQueryBuilder("queue='" + queue + "'", "*");

        // Create the searchObjectIdsViaExpression source
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(query);
        searchSourceBuilder.sort(new FieldSortBuilder("created").order(SortOrder.ASC));

        // Generate the actual request to send to ES.
        String docType = StringUtils.isBlank(docTypeOverride) ? MSG_DOC_TYPE : docTypeOverride;
        SearchRequest searchRequest = new SearchRequest(messageIndexPrefix + "*");
        searchRequest.types(docType);
        searchRequest.source(searchSourceBuilder);

        SearchResponse response = elasticSearchClient.search(searchRequest);
        return mapGetMessagesResponse(response);
    } catch (Exception e) {
        logger.error("Failed to get messages for queue: {}", queue, e);
    }
    return null;
}
 
Example #27
Source File: ElasticsearchNamespaceStore.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Iterator<SimpleNamespace> iterator() {

	SearchResponse searchResponse = clientProvider.getClient()
			.prepareSearch(index)
			.addSort(FieldSortBuilder.DOC_FIELD_NAME, SortOrder.ASC)
			.setQuery(QueryBuilders.constantScoreQuery(matchAllQuery()))
			.setSize(10000)
			.get();

	SearchHits hits = searchResponse.getHits();
	if (hits.totalHits > 10000) {
		throw new SailException("Namespace store only supports 10 000 items, found " + hits.totalHits);
	}

	return StreamSupport.stream(hits.spliterator(), false)
			.map(SearchHit::getSourceAsMap)
			.map(map -> new SimpleNamespace(map.get(PREFIX).toString(), map.get(NAMESPACE).toString()))
			.iterator();

}
 
Example #28
Source File: ElasticSearchRestDAOV5.java    From conductor with Apache License 2.0 5 votes vote down vote up
@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 query = QueryBuilders.boolQuery().must(stringQuery).must(filterQuery);

        // Create the searchObjectIdsViaExpression source
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(query);
        searchSourceBuilder.sort(new FieldSortBuilder("created").order(SortOrder.ASC));

        // Generate the actual request to send to ES.
        SearchRequest searchRequest = new SearchRequest(logIndexPrefix + "*");
        searchRequest.types(EVENT_DOC_TYPE);
        searchRequest.source(searchSourceBuilder);

        SearchResponse response = elasticSearchClient.search(searchRequest);

        return mapEventExecutionsResponse(response);
    } catch (Exception e) {
        logger.error("Failed to get executions for event: {}", event, e);
        throw new ApplicationException(ApplicationException.Code.BACKEND_ERROR, e.getMessage(), e);
    }
}
 
Example #29
Source File: ElasticsearchRepository.java    From staccato with Apache License 2.0 5 votes vote down vote up
protected void configureSort(SearchSourceBuilder searchSourceBuilder, SortExtension sort) {
    if (sort == null || sort.isEmpty()) {
        searchSourceBuilder
                .sort(new FieldSortBuilder("properties.datetime").order(SortOrder.DESC))
                .sort(new FieldSortBuilder("id").order(SortOrder.ASC));
        return;
    }

    for (SortExtension.SortTerm term : sort) {
        SortOrder sortOrder = (term.getDirection() == SortExtension.SortTerm.SortDirection.DESC) ?
                SortOrder.DESC : SortOrder.ASC;
        searchSourceBuilder.sort(new FieldSortBuilder(term.getField()).order(sortOrder));
    }
    searchSourceBuilder.sort(new FieldSortBuilder("id").order(SortOrder.DESC));
}
 
Example #30
Source File: TestElasticSearchRestDAOV5.java    From conductor with Apache License 2.0 5 votes vote down vote up
/**
 * Tries to find object ids for a given query in an index.
 *
 * @param indexName The name of the index.
 * @param queryBuilder The query to use for searching.
 * @param start The start to use.
 * @param size The total return size.
 * @param sortOptions A list of string options to sort in the form VALUE:ORDER; where ORDER is optional and can be either ASC OR DESC.
 * @param docType The document type to searchObjectIdsViaExpression for.
 *
 * @return The SearchResults which includes the count and IDs that were found.
 * @throws IOException If we cannot communicate with ES.
 */
private SearchResponse searchObjectIds(String indexName, QueryBuilder queryBuilder, int start, int size, List<String> sortOptions, String docType) throws IOException {

    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    searchSourceBuilder.query(queryBuilder);
    searchSourceBuilder.from(start);
    searchSourceBuilder.size(size);

    if (sortOptions != null && !sortOptions.isEmpty()) {

        for (String sortOption : sortOptions) {
            SortOrder order = SortOrder.ASC;
            String field = sortOption;
            int index = sortOption.indexOf(":");
            if (index > 0) {
                field = sortOption.substring(0, index);
                order = SortOrder.valueOf(sortOption.substring(index + 1));
            }
            searchSourceBuilder.sort(new FieldSortBuilder(field).order(order));
        }
    }

    // Generate the actual request to send to ES.
    SearchRequest searchRequest = new SearchRequest(indexName);
    searchRequest.types(docType);
    searchRequest.source(searchSourceBuilder);

    return elasticSearchClient.search(searchRequest);
}