org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder Java Examples

The following examples show how to use org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder. 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 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 #2
Source File: BookRepositoryTest.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@Test
public void shouldExecuteCustomSearchQueries() {

    Book book1 = new Book(RandomUtil.randomString(5, 10), "Custom Query", System.currentTimeMillis());
    Book book2 = new Book(RandomUtil.randomString(5, 10), null, System.currentTimeMillis());
    //indexing a book
    repository.saveAll(Arrays.asList(book1, book2));

    SearchQuery searchQuery = new NativeSearchQueryBuilder()
        .withQuery(matchAllQuery())
        .withFilter(existsQuery("name"))
        .withPageable(PageRequest.of(0, 10))
        .build();

    Page<Book> books = repository.search(searchQuery);
    Assertions.assertThat(books.getNumberOfElements()).isEqualTo(1);
}
 
Example #3
Source File: FuzzySearchTest.java    From Spring-Boot-Book with Apache License 2.0 6 votes vote down vote up
@Test
/**
 * Description: 前缀查询prefixQuery。
 */
public void prefixQuery() {
    // 查询条件
    NativeSearchQueryBuilder nativeSearchQueryBuilderQueryBuilder = new NativeSearchQueryBuilder();

    nativeSearchQueryBuilderQueryBuilder.withQuery(QueryBuilders.prefixQuery("name","士"));
    // 搜索,获取结果
    Page<Product>  products= productRepository.search(nativeSearchQueryBuilderQueryBuilder.build());
    for (Product product : products) {
        System.out.println(product);
    }

}
 
Example #4
Source File: ElasticsearchFacetTests.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@Test
public void shouldFilterResultByRegexForGivenQuery() {
    // given
    String facetName = "regex_authors";
    SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
        .withFilter(boolQuery().must(termQuery("title", "four")))
        .withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter()
            .fields("authors.untouched")
            .regex("Art.*")
            .build()).build();
    // when
    FacetedPage<Article> result = elasticsearchTemplate.queryForPage(searchQuery, Article.class);
    // then
    assertThat(result.getNumberOfElements(), is(equalTo(3)));

    TermResult facet = (TermResult) result.getFacet(facetName);

    assertThat(facet.getTerms().size(), is(1));

    Term term = facet.getTerms().get(0);
    assertThat(term.getTerm(), is(ARTUR_KONCZAK));
    assertThat(term.getCount(), is(2));
}
 
Example #5
Source File: ElasticsearchFacetTests.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@Test
public void shouldFilterResultByRegexForGivenQuery() {
    // given
    String facetName = "regex_authors";
    SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
        .withFilter(boolQuery().must(termQuery("title", "four")))
        .withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter()
            .fields("authors.untouched")
            .regex("Art.*")
            .build()).build();
    // when
    FacetedPage<Article> result = elasticsearchTemplate.queryForPage(searchQuery, Article.class);
    // then
    assertThat(result.getNumberOfElements(), is(equalTo(3)));

    TermResult facet = (TermResult) result.getFacet(facetName);

    assertThat(facet.getTerms().size(), is(1));

    Term term = facet.getTerms().get(0);
    assertThat(term.getTerm(), is(ARTUR_KONCZAK));
    assertThat(term.getCount(), is(2));
}
 
Example #6
Source File: QueryTest.java    From Spring-Boot-Book with Apache License 2.0 6 votes vote down vote up
@Test
/**
 * Description: 单个词查询
 */
public void termQuery() {
    // 构建查询条件
    NativeSearchQueryBuilder nativeSearchQueryBuilderQueryBuilder = new NativeSearchQueryBuilder();
    // 查询词,只能查询一个汉字,或者一个英文单词
    nativeSearchQueryBuilderQueryBuilder.withQuery(QueryBuilders.termQuery("name", "富"));
    // 搜索,获取结果
    Page<Product> products = productRepository.search(nativeSearchQueryBuilderQueryBuilder.build());
    // 总条数
    for (Product product : products) {
        System.out.println(product);
    }
}
 
Example #7
Source File: EkmKnowledgeRepositoryImpl.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@Override
public EkmKnowledge findByIdAndOrgi(String id, String orgi) {
	
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	BoolQueryBuilder bq = QueryBuilders.boolQuery() ; 
	bq.must(QueryBuilders.termQuery("id", id)) ;
	bq.must(QueryBuilders.termQuery("orgi", orgi)) ;
	boolQueryBuilder.must(bq); 
	
	NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder) ;
	Page<EkmKnowledge> knowledgeList = null ;
	if(elasticsearchTemplate.indexExists(EkmKnowledge.class)){
		knowledgeList = elasticsearchTemplate.queryForPage(searchQueryBuilder.build() , EkmKnowledge.class ) ;
    }
	if (knowledgeList!=null && knowledgeList.getContent().size()>0) {
		return knowledgeList.getContent().get(0);
	}else {
		return null ;
	}
	
}
 
Example #8
Source File: QueryTest.java    From Spring-Boot-Book with Apache License 2.0 6 votes vote down vote up
@Test
/**
 * Description: 多参数termsQuery
 */
public void termsQuery() {
    // 构建查询条件
    NativeSearchQueryBuilder nativeSearchQueryBuilderQueryBuilder = new NativeSearchQueryBuilder();
    // 查询词,只能查询一个汉字,或者一个英文单词
    nativeSearchQueryBuilderQueryBuilder.withQuery(QueryBuilders.termsQuery("name", "富","帅"));
    // 搜索,获取结果
    Page<Product> products = productRepository.search(nativeSearchQueryBuilderQueryBuilder.build());
    // 总条数
    for (Product product : products) {
        System.out.println(product);
    }
}
 
Example #9
Source File: FuzzySearchTest.java    From Spring-Boot-Book with Apache License 2.0 6 votes vote down vote up
@Test
/**
 * Description:相似内容查询。
 */
public void multiMoreLikeThisQuery() {
    // 查询条件
    NativeSearchQueryBuilder nativeSearchQueryBuilderQueryBuilder = new NativeSearchQueryBuilder();
    //  左右模糊
    nativeSearchQueryBuilderQueryBuilder.withQuery(QueryBuilders.moreLikeThisQuery(new String[]{"name"}, new String[]{"红"}, null));
    nativeSearchQueryBuilderQueryBuilder.withQuery(QueryBuilders.moreLikeThisQuery(new String[]{"name"}, new String[]{"红"}, null));
    nativeSearchQueryBuilderQueryBuilder.withQuery(QueryBuilders.moreLikeThisQuery(new String[]{"name"}, new String[]{"红"}, null));
    // 搜索,获取结果
    Page<Product> products = productRepository.search(nativeSearchQueryBuilderQueryBuilder.build());
    for (Product product : products) {
        System.out.println(product);
    }
}
 
Example #10
Source File: PersonRepositoryTest.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 自定义高级查询
 */
@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 #11
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 #12
Source File: EkmKnowledgeTimesRepositoryImpl.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@Override
public List<EkmKnowledgeTimes> findByKbidAndOrgi(String kbid, String orgi) {
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	BoolQueryBuilder bq = QueryBuilders.boolQuery() ; 
	bq.must(QueryBuilders.termQuery("kbid", kbid)) ;
	bq.must(QueryBuilders.termQuery("orgi", orgi)) ;
	boolQueryBuilder.must(bq); 
	
	NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder) ;
	Page<EkmKnowledgeTimes> knowledgeTimesList = null ;
	if(elasticsearchTemplate.indexExists(EkmKnowledgeTimes.class)){
		knowledgeTimesList = elasticsearchTemplate.queryForPage(searchQueryBuilder.build() , EkmKnowledgeTimes.class ) ;
    }
	
	return knowledgeTimesList.getContent();
}
 
Example #13
Source File: ByPageTest.java    From Spring-Boot-Book with Apache License 2.0 6 votes vote down vote up
@Test
/**
 * Description: 分页查询
 */
public void termQuery() {
    // 分页:
    int page = 0;
    int size = 1;//每页文档数

    // 构建查询条件
    NativeSearchQueryBuilder nativeSearchQueryBuilderQueryBuilder = new NativeSearchQueryBuilder();
    // 查询词,只能查询一个汉字,或者一个英文单词
    nativeSearchQueryBuilderQueryBuilder.withQuery(QueryBuilders.termQuery("name", "富"));
    // 搜索,获取结果
    nativeSearchQueryBuilderQueryBuilder.withPageable(PageRequest.of(page, size));
    Page<Product> products = productRepository.search(nativeSearchQueryBuilderQueryBuilder.build());
    // 总条数
      for (Product product : products) {
        System.out.println(product);
    }

}
 
Example #14
Source File: EkmKnowledgeMasterRepositoryImpl.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@Override
public List<EkmKnowledgeMaster> findByOrgiAndDatastatus(String orgi, boolean datastatus) {
	
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	BoolQueryBuilder bq = QueryBuilders.boolQuery() ; 
	bq.must(QueryBuilders.termQuery("datastatus", datastatus)) ;
	bq.must(QueryBuilders.termQuery("orgi", orgi)) ;
	boolQueryBuilder.must(bq); 
	
	NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withPageable(new PageRequest(0, 100000)) ;
	Page<EkmKnowledgeMaster> knowledgeList = null ;
	if(elasticsearchTemplate.indexExists(EkmKnowledgeMaster.class)){
		knowledgeList = elasticsearchTemplate.queryForPage(searchQueryBuilder.build() , EkmKnowledgeMaster.class ) ;
    }
	
	return knowledgeList.getContent();
}
 
Example #15
Source File: ElasticsearchFacetTests.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@Test
public void shouldReturnFacetedAuthorsForGivenFilteredQuery() {
    // given
    String facetName = "fauthors";
    SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
        .withFilter(boolQuery().must(termQuery("title", "four")))
        .withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("authors.untouched").build())
        .build();
    // when
    FacetedPage<Article> result = elasticsearchTemplate.queryForPage(searchQuery, Article.class);
    // then
    assertThat(result.getNumberOfElements(), is(equalTo(3)));

    TermResult facet = (TermResult) result.getFacet(facetName);
    Term term = facet.getTerms().get(0);
    assertThat(term.getTerm(), is(RIZWAN_IDREES));
    assertThat(term.getCount(), is(3));

    term = facet.getTerms().get(1);
    assertThat(term.getTerm(), is(ARTUR_KONCZAK));
    assertThat(term.getCount(), is(2));

    term = facet.getTerms().get(2);
    assertThat(term.getTerm(), is(MOHSIN_HUSEN));
    assertThat(term.getCount(), is(1));
}
 
Example #16
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 #17
Source File: EkmKnowledgeMasterRepositoryImpl.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@Override
public EkmKnowledgeMaster findByIdAndOrgi(String id, String orgi) {
	
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	BoolQueryBuilder bq = QueryBuilders.boolQuery() ; 
	bq.must(QueryBuilders.termQuery("id", id)) ;
	bq.must(QueryBuilders.termQuery("orgi", orgi)) ;
	boolQueryBuilder.must(bq); 
	
	NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder) ;
	Page<EkmKnowledgeMaster> knowledgeList = null ;
	if(elasticsearchTemplate.indexExists(EkmKnowledgeMaster.class)){
		knowledgeList = elasticsearchTemplate.queryForPage(searchQueryBuilder.build() , EkmKnowledgeMaster.class ) ;
    }
	if (knowledgeList!=null && knowledgeList.getContent().size()>0) {
		return knowledgeList.getContent().get(0);
	}else {
		return null ;
	}
}
 
Example #18
Source File: EkmKnowledgeRepositoryImpl.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@Override
public List<EkmKnowledge> findByKnowbaseidAndDatastatusAndOrgi(String knowbaseid, boolean datastatus, String orgi) {
	
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	BoolQueryBuilder bq = QueryBuilders.boolQuery() ; 
	bq.must(QueryBuilders.termQuery("datastatus", datastatus)) ;
	bq.must(QueryBuilders.termQuery("orgi", orgi)) ;
	if(!StringUtils.isBlank(knowbaseid)){
		bq.must(termQuery("knowbaseid" , knowbaseid)) ;
	}else{
		bq.must(termQuery("knowbaseid" , UKDataContext.UKEFU_SYSTEM_NO_DAT)) ;
	}
	boolQueryBuilder.must(bq); 
	
	NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder) ;
	Page<EkmKnowledge> knowledgeList = null ;
	if(elasticsearchTemplate.indexExists(EkmKnowledge.class)){
		knowledgeList = elasticsearchTemplate.queryForPage(searchQueryBuilder.build() , EkmKnowledge.class ) ;
    }
	
	return knowledgeList.getContent();
}
 
Example #19
Source File: CityESServiceImpl.java    From springboot-learning-example with Apache License 2.0 6 votes vote down vote up
/**
 * 根据搜索词构造搜索查询语句
 *
 * 代码流程:
 *      - 权重分查询
 *      - 短语匹配
 *      - 设置权重分最小值
 *      - 设置分页参数
 *
 * @param pageNumber 当前页码
 * @param pageSize 每页大小
 * @param searchContent 搜索内容
 * @return
 */
private SearchQuery getCitySearchQuery(Integer pageNumber, Integer pageSize,String searchContent) {
    // 短语匹配到的搜索词,求和模式累加权重分
    // 权重分查询 https://www.elastic.co/guide/cn/elasticsearch/guide/current/function-score-query.html
    //   - 短语匹配 https://www.elastic.co/guide/cn/elasticsearch/guide/current/phrase-matching.html
    //   - 字段对应权重分设置,可以优化成 enum
    //   - 由于无相关性的分值默认为 1 ,设置权重分最小值为 10
    FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery()
            .add(QueryBuilders.matchPhraseQuery("name", searchContent),
            ScoreFunctionBuilders.weightFactorFunction(1000))
            .add(QueryBuilders.matchPhraseQuery("description", searchContent),
            ScoreFunctionBuilders.weightFactorFunction(500))
            .scoreMode(SCORE_MODE_SUM).setMinScore(MIN_SCORE);

    // 分页参数
    Pageable pageable = new PageRequest(pageNumber, pageSize);
    return new NativeSearchQueryBuilder()
            .withPageable(pageable)
            .withQuery(functionScoreQueryBuilder).build();
}
 
Example #20
Source File: SearchService.java    From leyou with Apache License 2.0 6 votes vote down vote up
/**
 * 构建基本查询条件
 *
 * @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 #21
Source File: EkmKnowledgeRepositoryImpl.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@Override
public List<EkmKnowledge> findByOrgiAndDatastatus(String orgi, boolean datastatus) {
	
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	BoolQueryBuilder bq = QueryBuilders.boolQuery() ; 
	bq.must(QueryBuilders.termQuery("datastatus", datastatus)) ;
	bq.must(QueryBuilders.termQuery("orgi", orgi)) ;
	boolQueryBuilder.must(bq); 
	
	NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder) ;
	Page<EkmKnowledge> knowledgeList = null ;
	if(elasticsearchTemplate.indexExists(EkmKnowledge.class)){
		knowledgeList = elasticsearchTemplate.queryForPage(searchQueryBuilder.build() , EkmKnowledge.class ) ;
    }
	
	return knowledgeList.getContent();
}
 
Example #22
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 #23
Source File: SpringDataQueryTest.java    From code with Apache License 2.0 6 votes vote down vote up
/**
 * 排序
 */
@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 #24
Source File: Queries.java    From klask-io with GNU General Public License v3.0 6 votes vote down vote up
/**
 * construct a searchQuery with a number of fragments to highlight per results.
 *
 * @param query
 * @param p
 * @param numberOfFragments
 * @return
 */
public static NativeSearchQueryBuilder constructQueryWithHighlight(String query, Pageable p, int numberOfFragments) {
    return new NativeSearchQueryBuilder()
        //.withQuery(termQuery("content", query))
        .withQuery(queryBuilder(query))
        //.withFields("content", "name")
        .withPageable(p)
        //exclu le content de la recherche pour alléger les requêtes
        .withSourceFilter(
            new FetchSourceFilterBuilder()
                .withExcludes("content")
                .build()
        )

        .withHighlightFields(
            new HighlightBuilder.Field("content")
                .preTags("<mark>")
                .postTags("</mark>")

                .numOfFragments(numberOfFragments)
                .fragmentSize(150)
        );
}
 
Example #25
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 #26
Source File: ElasticsearchFacetTests.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@Test
public void shouldReturnFacetedAuthorsForGivenFilteredQuery() {
    // given
    String facetName = "fauthors";
    SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
        .withFilter(boolQuery().must(termQuery("title", "four")))
        .withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("authors.untouched").build())
        .build();
    // when
    FacetedPage<Article> result = elasticsearchTemplate.queryForPage(searchQuery, Article.class);
    // then
    assertThat(result.getNumberOfElements(), is(equalTo(3)));

    TermResult facet = (TermResult) result.getFacet(facetName);
    Term term = facet.getTerms().get(0);
    assertThat(term.getTerm(), is(RIZWAN_IDREES));
    assertThat(term.getCount(), is(3));

    term = facet.getTerms().get(1);
    assertThat(term.getTerm(), is(ARTUR_KONCZAK));
    assertThat(term.getCount(), is(2));

    term = facet.getTerms().get(2);
    assertThat(term.getTerm(), is(MOHSIN_HUSEN));
    assertThat(term.getCount(), is(1));
}
 
Example #27
Source File: NotificationMessageProcessor.java    From oneops with Apache License 2.0 6 votes vote down vote up
/**
 * Update ops notifications to CIs
 *
 * @param notificationMsg notification message to process
 */
private void processNotificationMsg(CmsNotificationSearch notificationMsg) {
    String id = String.valueOf(notificationMsg.getCmsId());

    SearchQuery searchQuery = new NativeSearchQueryBuilder()
            .withIndices(indexer.getIndexName())
            .withTypes("ci").withQuery(queryStringQuery(id).field("ciId"))
            .build();

    List<CmsCISearch> ciList = indexer.getTemplate().queryForList(searchQuery, CmsCISearch.class);

    if (!ciList.isEmpty()) {
        CmsCISearch ciSearch = ciList.get(0);
        if ("bom.Compute".equals(ciSearch.getCiClassName())) {
            String hypervisor = ciSearch.getCiAttributes().get("hypervisor");
            if (hypervisor != null) {
                notificationMsg.setHypervisor(hypervisor);
            }
        }
        ciSearch.setOps(notificationMsg);
        indexer.index(id, "ci", GSON_ES.toJson(ciSearch));
        logger.info("updated ops notification for ci id::" + id);
    } else {
        logger.warn("ci record not found for id::" + id);
    }
}
 
Example #28
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 #29
Source File: BookRepositoryTest.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@Test
public void shouldReturnBooksForGivenBucket() {
    Book book1 = new Book(RandomUtil.randomString(5, 10), "test1", System.currentTimeMillis());
    Book book2 = new Book(RandomUtil.randomString(5, 10), "test2", System.currentTimeMillis());

    Map<Integer, Collection<String>> map1 = new HashMap<>();
    map1.put(1, Arrays.asList("test1", "test2"));

    Map<Integer, Collection<String>> map2 = new HashMap<>();
    map2.put(1, Arrays.asList("test3", "test4"));

    book1.setBuckets(map1);
    book2.setBuckets(map2);

    repository.saveAll(Arrays.asList(book1, book2));

    SearchQuery searchQuery = new NativeSearchQueryBuilder()
        .withQuery(nestedQuery("buckets", termQuery("buckets.1", "test3"), ScoreMode.Total))
        .build();

    Page<Book> books = repository.search(searchQuery);
    Assertions.assertThat(books.getContent()).hasSize(1);
}
 
Example #30
Source File: EkmKnowledgeRepositoryImpl.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@Override
public EkmKnowledge findByTitleAndOrgi(String title, String orgi) {
	
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	BoolQueryBuilder bq = QueryBuilders.boolQuery() ; 
	bq.must(QueryBuilders.termQuery("title", title)) ;
	bq.must(QueryBuilders.termQuery("orgi", orgi)) ;
	boolQueryBuilder.must(bq); 
	
	NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder) ;
	Page<EkmKnowledge> knowledgeList = null ;
	if(elasticsearchTemplate.indexExists(EkmKnowledge.class)){
		knowledgeList = elasticsearchTemplate.queryForPage(searchQueryBuilder.build() , EkmKnowledge.class ) ;
    }
	
	return knowledgeList.getContent().get(0);
}