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

The following examples show how to use org.springframework.data.elasticsearch.core.query.SearchQuery. 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: KbsTopicCommentRepositoryImpl.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@Override
public Page<KbsTopicComment> findByCon(NativeSearchQueryBuilder searchQueryBuilder , String field , String aggname,  String q , final int p , final int ps) {
	Page<KbsTopicComment> pages  = null ;
	if(!StringUtils.isBlank(q)){
	   	searchQueryBuilder.withQuery(new QueryStringQueryBuilder(q).defaultOperator(Operator.AND)) ;
	}
   	SearchQuery searchQuery = searchQueryBuilder.build();
    if(elasticsearchTemplate.indexExists(KbsTopicComment.class)){
    	if(!StringUtils.isBlank(q)){
    		pages = elasticsearchTemplate.queryForPage(searchQuery, KbsTopicComment.class  , new UKResultMapper());
    	}else{
    		pages = elasticsearchTemplate.queryForPage(searchQuery, KbsTopicComment.class , new UKAggTopResultExtractor(field , aggname));
    	}
    }
    return pages ; 
}
 
Example #4
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 #5
Source File: ElasticsearchTransactionRepository.java    From servicecomb-pack with Apache License 2.0 6 votes vote down vote up
public Map<String, Long> getTransactionStatistics() {
  TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders
      .terms("count_group_by_state").field("state.keyword");
  SearchQuery searchQuery = new NativeSearchQueryBuilder()
      .withIndices(INDEX_NAME)
      .addAggregation(termsAggregationBuilder)
      .build();
  return this.template.query(searchQuery, response -> {
    Map<String, Long> statistics = new HashMap<>();
    if (response.getHits().totalHits > 0) {
      final StringTerms groupState = response.getAggregations().get("count_group_by_state");
      statistics = groupState.getBuckets()
          .stream()
          .collect(Collectors.toMap(MultiBucketsAggregation.Bucket::getKeyAsString,
              MultiBucketsAggregation.Bucket::getDocCount));
    }
    return statistics;
  });
}
 
Example #6
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 #7
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 #8
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 #9
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 #10
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 #11
Source File: EsServiceImpl.java    From mall with Apache License 2.0 6 votes vote down vote up
@Log
@Override
public EsSearchResponse query(EsSearchRequest esSearchRequest) {

    if (Objects.isNull(esSearchRequest)) {
        log.error("esSearchRequest is empty....");
        return new EsSearchResponse();
    }

    // 建立dsl搜索语句
    SearchQuery searchQuery = buildSearchQuery(esSearchRequest);

    log.info("search from Elasticsearch and DSL :{}", searchQuery.getQuery().toString());

    return elasticsearchTemplate.query(searchQuery, searchResponse -> {
        log.debug("result:" + searchResponse);
        return EsSearchResponse.buildEsSearchResponse(searchResponse, resultsMapper);
    });
}
 
Example #12
Source File: EsServiceImpl.java    From mall with Apache License 2.0 6 votes vote down vote up
/**
 * 构造查询语句
 *
 * @param esSearchRequest 查询请求
 * @return 返回查询语句
 */
private SearchQuery buildSearchQuery(EsSearchRequest esSearchRequest) {
    //设置查询主体
    NativeSearchQueryBuilder nativeSearchQueryBuilder = esSearchRequest.buildNativeSearchQueryBuilder().withPageable(esSearchRequest.buildPageable()).withQuery(esSearchRequest.buildBoolQueryBuilder());

    // 设置排序
    addSort(nativeSearchQueryBuilder, esSearchRequest);

    // 聚合
    if (esSearchRequest.isNeddAgg()) {
        // 增加聚合
        addAttributeAggregation(nativeSearchQueryBuilder);
    }


    if (esSearchRequest.isHightLight()) {
        // 设置高亮
        setHighlighted(nativeSearchQueryBuilder);
    }

    return nativeSearchQueryBuilder.build();
}
 
Example #13
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 #14
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 #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 shouldExcludeTermsFromFacetedAuthorsForGivenQuery() {
    // given
    String facetName = "fauthors";
    SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
        .withFilter(boolQuery().must(termQuery("title", "four")))
        .withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter()
            .fields("authors.untouched")
            .excludeTerms(RIZWAN_IDREES, ARTUR_KONCZAK)
            .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(MOHSIN_HUSEN));
    assertThat(term.getCount(), is(1));
}
 
Example #16
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 #17
Source File: CityESServiceImpl.java    From springboot-learning-example with Apache License 2.0 6 votes vote down vote up
@Override
public List<City> searchCity(Integer pageNumber, Integer pageSize, String searchContent) {

    // 校验分页参数
    if (pageSize == null || pageSize <= 0) {
        pageSize = PAGE_SIZE;
    }

    if (pageNumber == null || pageNumber < DEFAULT_PAGE_NUMBER) {
        pageNumber = DEFAULT_PAGE_NUMBER;
    }

    LOGGER.info("\n searchCity: searchContent [" + searchContent + "] \n ");

    // 构建搜索查询
    SearchQuery searchQuery = getCitySearchQuery(pageNumber,pageSize,searchContent);

    LOGGER.info("\n searchCity: searchContent [" + searchContent + "] \n DSL  = \n " + searchQuery.getQuery().toString());

    Page<City> cityPage = cityRepository.search(searchQuery);
    return cityPage.getContent();
}
 
Example #18
Source File: CityESServiceImpl.java    From springboot-learning-example with Apache License 2.0 6 votes vote down vote up
@Override
public List<City> searchCity(Integer pageNumber,
                             Integer pageSize,
                             String searchContent) {
    // 分页参数
    Pageable pageable = new PageRequest(pageNumber, pageSize);

    // Function Score Query
    FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery()
            .add(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("cityname", searchContent)),
                ScoreFunctionBuilders.weightFactorFunction(1000))
            .add(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("description", searchContent)),
                    ScoreFunctionBuilders.weightFactorFunction(100));

    // 创建搜索 DSL 查询
    SearchQuery searchQuery = new NativeSearchQueryBuilder()
            .withPageable(pageable)
            .withQuery(functionScoreQueryBuilder).build();

    LOGGER.info("\n searchCity(): searchContent [" + searchContent + "] \n DSL  = \n " + searchQuery.getQuery().toString());

    Page<City> searchPageResults = cityRepository.search(searchQuery);
    return searchPageResults.getContent();
}
 
Example #19
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 shouldReturnFacetedYearsForNativeFacet() {

    // given
    String facetName = "fyears";
    SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build();
    // when
    FacetedPage<Article> result = elasticsearchTemplate.queryForPage(searchQuery, Article.class);
    // then
    assertThat(result.getNumberOfElements(), is(equalTo(4)));

    TermResult facet = (TermResult) result.getFacet(facetName);
    assertThat(facet.getTerms().size(), is(equalTo(3)));

    Term term = facet.getTerms().get(0);
    assertThat(term.getTerm(), is(Integer.toString(YEAR_2000)));
    assertThat(term.getCount(), is(3));

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

    term = facet.getTerms().get(2);
    assertThat(term.getTerm(), is(Integer.toString(YEAR_2002)));
    assertThat(term.getCount(), is(1));
}
 
Example #20
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 shouldReturnAllTermsForGivenQuery() {
    // given
    String facetName = "all_authors";
    SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
        .withFilter(boolQuery().must(termQuery("title", "four")))
        .withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter()
            .fields("authors.untouched")
            .allTerms()
            .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(4));
}
 
Example #21
Source File: NestedObjectTests.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@Test
public void shouldSearchUsingNestedQueryOnMultipleLevelNestedObject() {
    //given
    List<IndexQuery> indexQueries = createPerson();

    //when
    elasticsearchTemplate.putMapping(PersonMultipleLevelNested.class);
    elasticsearchTemplate.bulkIndex(indexQueries);
    elasticsearchTemplate.refresh(PersonMultipleLevelNested.class);

    //then
    BoolQueryBuilder builder = boolQuery();
    builder.must(nestedQuery("girlFriends", termQuery("girlFriends.type", "temp"), ScoreMode.Total))
        .must(nestedQuery("girlFriends.cars", termQuery("girlFriends.cars.name", "Ford".toLowerCase()),
            ScoreMode.Total));

    SearchQuery searchQuery = new NativeSearchQueryBuilder()
        .withQuery(builder)
        .build();

    Page<PersonMultipleLevelNested> personIndexed =
        elasticsearchTemplate.queryForPage(searchQuery, PersonMultipleLevelNested.class);
    assertThat(personIndexed, is(notNullValue()));
    assertThat(personIndexed.getTotalElements(), is(1L));
    assertThat(personIndexed.getContent().get(0).getId(), is("1"));
}
 
Example #22
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 #23
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 #24
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 #25
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 shouldExcludeTermsFromFacetedAuthorsForGivenQuery() {
    // given
    String facetName = "fauthors";
    SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
        .withFilter(boolQuery().must(termQuery("title", "four")))
        .withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter()
            .fields("authors.untouched")
            .excludeTerms(RIZWAN_IDREES, ARTUR_KONCZAK)
            .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(MOHSIN_HUSEN));
    assertThat(term.getCount(), is(1));
}
 
Example #26
Source File: UserRepositoryTest.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@Test
public void testSearch() throws IllegalAccessException {
    List<User> users = new ArrayList<>();
    for (int i = 0; i < 1000; i++) {
        User user = new User(String.valueOf(i), RandomUtil.randomChineseName(), RandomUtils.nextInt(18, 99),
            RandomUtil.randomString(6, 10), RandomUtil.randomEmail());
        users.add(user);
    }
    userRepository.saveAll(users);

    UserQuery userQuery = new UserQuery();
    userQuery.setUsername("张");
    SearchQuery searchQuery = QueryFeildToQueryBuilderUtil.transQueryDto2Condition(userQuery);

    Page<User> page = userRepository.search(searchQuery);
    System.out.println("Total Match: " + page.getTotalElements());
    page.getContent().forEach(System.out::println);
}
 
Example #27
Source File: NestedObjectTests.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@Test
public void shouldSearchUsingNestedQueryOnMultipleLevelNestedObject() {
    //given
    List<IndexQuery> indexQueries = createPerson();

    //when
    elasticsearchTemplate.putMapping(PersonMultipleLevelNested.class);
    elasticsearchTemplate.bulkIndex(indexQueries);
    elasticsearchTemplate.refresh(PersonMultipleLevelNested.class);

    //then
    BoolQueryBuilder builder = boolQuery();
    builder.must(nestedQuery("girlFriends", termQuery("girlFriends.type", "temp"), ScoreMode.Total))
        .must(nestedQuery("girlFriends.cars", termQuery("girlFriends.cars.name", "Ford".toLowerCase()),
            ScoreMode.Total));

    SearchQuery searchQuery = new NativeSearchQueryBuilder()
        .withQuery(builder)
        .build();

    Page<PersonMultipleLevelNested> personIndexed =
        elasticsearchTemplate.queryForPage(searchQuery, PersonMultipleLevelNested.class);
    assertThat(personIndexed, is(notNullValue()));
    assertThat(personIndexed.getTotalElements(), is(1L));
    assertThat(personIndexed.getContent().get(0).getId(), is("1"));
}
 
Example #28
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 shouldReturnAllTermsForGivenQuery() {
    // given
    String facetName = "all_authors";
    SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
        .withFilter(boolQuery().must(termQuery("title", "four")))
        .withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter()
            .fields("authors.untouched")
            .allTerms()
            .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(4));
}
 
Example #29
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 #30
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 shouldReturnFacetedYearsForNativeFacet() {

    // given
    String facetName = "fyears";
    SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build();
    // when
    FacetedPage<Article> result = elasticsearchTemplate.queryForPage(searchQuery, Article.class);
    // then
    assertThat(result.getNumberOfElements(), is(equalTo(4)));

    TermResult facet = (TermResult) result.getFacet(facetName);
    assertThat(facet.getTerms().size(), is(equalTo(3)));

    Term term = facet.getTerms().get(0);
    assertThat(term.getTerm(), is(Integer.toString(YEAR_2000)));
    assertThat(term.getCount(), is(3));

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

    term = facet.getTerms().get(2);
    assertThat(term.getTerm(), is(Integer.toString(YEAR_2002)));
    assertThat(term.getCount(), is(1));
}