org.elasticsearch.index.query.Operator Java Examples

The following examples show how to use org.elasticsearch.index.query.Operator. 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: SearchService.java    From leyou with Apache License 2.0 5 votes vote down vote up
/**
 * 构建bool查询构建器
 *
 * @param request
 * @return
 */
private BoolQueryBuilder buildBooleanQueryBuilder(SearchRequest request) {
    BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

    // 添加基本查询条件
    boolQueryBuilder.must(QueryBuilders.matchQuery("all", request.getKey()).operator(Operator.AND));

    // 添加过滤条件
    if (CollectionUtils.isEmpty(request.getFilter())) {
        return boolQueryBuilder;
    }
    for (Map.Entry<String, String> entry : request.getFilter().entrySet()) {
        String key = entry.getKey();
        // 如果过滤条件是“品牌”, 过滤的字段名:brandId
        if (StringUtils.equals("品牌", key)) {
            key = "brandId";
        } else if (StringUtils.equals("分类", key)) {
            // 如果是“分类”,过滤字段名:cid3
            key = "cid3";
        } else {
            // 如果是规格参数名,过滤字段名:specs.key.keyword
            key = "specs." + key + ".keyword";
        }
        boolQueryBuilder.filter(QueryBuilders.termQuery(key, entry.getValue()));
    }

    return boolQueryBuilder;
}
 
Example #2
Source File: YaCyQuery.java    From yacy_grid_mcp with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static QueryBuilder simpleQueryBuilder(String q, boolean or, Boosts boosts) {
    if (q.equals("yacyall")) return new MatchAllQueryBuilder();
    final MultiMatchQueryBuilder qb = QueryBuilders
            .multiMatchQuery(q)
            .operator(or ? Operator.OR : Operator.AND)
            .zeroTermsQuery(ZeroTermsQuery.ALL);
    boosts.forEach((mapping, boost) -> qb.field(mapping.getMapping().name(), boost));
    return qb;
}
 
Example #3
Source File: ElasticSearchQueryGenerator.java    From Stargraph with MIT License 5 votes vote down vote up
@Override
public SearchQueryHolder findEntityInstances(ModifiableSearchParams searchParams, int maxEdits) {
    QueryBuilder queryBuilder = matchQuery("value", searchParams.getSearchTerm())
            .fuzziness(maxEdits).fuzzyTranspositions(false).operator(Operator.AND);

    return new ElasticQueryHolder(queryBuilder, searchParams);
}
 
Example #4
Source File: ElasticQueryBuilder.java    From vind with Apache License 2.0 5 votes vote down vote up
public static SearchSourceBuilder buildExperimentalSuggestionQuery(
            ExecutableSuggestionSearch search,
            DocumentFactory factory) {

        final String searchContext = search.getSearchContext();
        final SearchSourceBuilder searchSource = new SearchSourceBuilder();

        final BoolQueryBuilder baseQuery = QueryBuilders.boolQuery();

        final String[] suggestionFieldNames = Stream.of(getSuggestionFieldNames(search, factory, searchContext))
                .map(name -> name.concat("_experimental"))
                .toArray(String[]::new);

        final MultiMatchQueryBuilder suggestionQuery = QueryBuilders
                .multiMatchQuery(search.getInput(),suggestionFieldNames)
                .type(MultiMatchQueryBuilder.Type.BEST_FIELDS)
                .operator(Operator.OR);

        baseQuery.must(suggestionQuery);

//        if(search.getTimeZone() != null) {
//            query.set(CommonParams.TZ,search.getTimeZone());
//        }

        baseQuery.filter(buildFilterQuery(search.getFilter(), factory, searchContext));

        searchSource.query(baseQuery);

        final HighlightBuilder highlighter = new HighlightBuilder().numOfFragments(0);
        Stream.of(suggestionFieldNames)
                .forEach(highlighter::field);

        searchSource.highlighter(highlighter);
        searchSource.trackScores(SearchConfiguration.get(SearchConfiguration.SEARCH_RESULT_SHOW_SCORE, true));
        searchSource.fetchSource(true);

        //TODO if nested document search is implemented

        return searchSource;
    }
 
Example #5
Source File: SpiderInfoDAO.java    From Gather-Platform with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 根据domain获取结果
 *
 * @param domain 网站域名
 * @param size   每页数量
 * @param page   页码
 * @return
 */
public List<SpiderInfo> getByDomain(String domain, int size, int page) {
    SearchRequestBuilder searchRequestBuilder = client.prepareSearch(INDEX_NAME)
            .setTypes(TYPE_NAME)
            .setQuery(QueryBuilders.matchQuery("domain", domain).operator(Operator.AND))
            .setSize(size).setFrom(size * (page - 1));
    SearchResponse response = searchRequestBuilder.execute().actionGet();
    return warpHits2List(response.getHits());
}
 
Example #6
Source File: SpiderInfoDAO.java    From spider with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 根据domain获取结果
 *
 * @param domain 网站域名
 * @param size   每页数量
 * @param page   页码
 * @return
 */
public List<SpiderInfo> getByDomain(String domain, int size, int page) {
    SearchRequestBuilder searchRequestBuilder = client.prepareSearch(INDEX_NAME)
            .setTypes(TYPE_NAME)
            .setQuery(QueryBuilders.matchQuery("domain", domain).operator(Operator.AND))
            .setSize(size).setFrom(size * (page - 1));
    SearchResponse response = searchRequestBuilder.execute().actionGet();
    return warpHits2List(response.getHits());
}
 
Example #7
Source File: ElasticSearchQueryManualTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenFullTitle_whenRunMatchQuery_thenDocIsFound() {
    final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "Search engines").operator(Operator.AND))
        .build();
    final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
    assertEquals(1, articles.getTotalHits());
}
 
Example #8
Source File: ElasticSearchQueryManualTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenPhraseWithType_whenUseFuzziness_thenQueryMatches() {
    final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "spring date elasticserch").operator(Operator.AND)
        .fuzziness(Fuzziness.ONE)
        .prefixLength(3))
        .build();

    final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));

    assertEquals(1, articles.getTotalHits());
}
 
Example #9
Source File: ItemByEsServiceImpl.java    From springBoot with MIT License 4 votes vote down vote up
@Override
public Result<PageInfo<ItemByEsVo>> searchByNative(ItemByEsVo itemByEsVo) {
    // 统计查询时间,这里开始
    Instant start = Instant.now();

    // 构造查询条件
    QueryBuilder matchQuery = QueryBuilders.matchQuery("title", itemByEsVo.getTitle())
            .analyzer("standard") //分词器
            .operator(Operator.OR);//or查询 Operator.OR、and查询Operator.AND

    // 设置高亮,使用默认的highlighter高亮器
    HighlightBuilder highlightBuilder = new HighlightBuilder()
            .field("title") //需要高亮的域(字段)
            .preTags("<span style=\"color:red;\">") //前缀
            .postTags("</span>"); //后缀

    // 设置查询字段
    SearchResponse response = client.prepareSearch("book")
            .setQuery(matchQuery)
            .highlighter(highlightBuilder)
            // 设置一次返回的文档数量
            .setSize(10)
            .get();

    // 返回搜索结果
    SearchHits hits = response.getHits();

    // 统计搜索结束时间
    Instant end = Instant.now();

    ArrayList novel = new ArrayList();
    for (int i = 0; i < hits.getTotalHits(); i++) {
        // 得到SearchHit对象
        SearchHit hit = hits.getAt(i);
        // 遍历结果,使用HashMap存放
        LinkedHashMap map = new LinkedHashMap();
        map.put("Source As String", hit.getSourceAsString());
        // 返回String格式的文档结果
        System.out.println("Source As String:" + hit.getSourceAsString());
        map.put("Source As Map", hit.getSourceAsMap());
        // 返回Map格式的文档结果
        System.out.println("Source As Map:" + hit.getSourceAsMap());
        // 返回文档所在的索引
        map.put("Index", hit.getIndex());
        System.out.println("Index:" + hit.getIndex());
        // 返回文档所在的类型
        map.put("Type", hit.getType());
        System.out.println("Type:" + hit.getType());
        // 返回文档所在的ID编号
        map.put("Id", hit.getId());
        System.out.println("Id:" + hit.getId());
        // 返回指定字段的内容,例如这里返回完整的title的内容
        map.put("Title", hit.getSourceAsMap().get("title"));
        System.out.println("title: " + hit.getSourceAsMap().get("title"));
        // 返回文档的评分
        map.put("Scope", hit.getScore());
        System.out.println("Scope:" + hit.getScore());
        // 返回文档的高亮字段
        Text[] text = hit.getHighlightFields().get("title").getFragments();
        StringBuilder hight = new StringBuilder();
        if (text != null) {
            for (Text str : text) {
                hight.append(str);
                System.out.println(str.toString());
            }
        }
        map.put("Highlight", hight.toString());
        novel.add(map);
    }

    System.out.println(novel);
    System.out.println("共查出"+hits.getTotalHits()+"条记录!");
    System.out.println("共耗时"+ Duration.between(start, end).toMillis()+"ms");
    return null;
}
 
Example #10
Source File: Paramer.java    From elasticsearch-sql with Apache License 2.0 4 votes vote down vote up
public static Paramer parseParamer(SQLMethodInvokeExpr method) throws SqlParseException {
	Paramer instance = new Paramer();
	List<SQLExpr> parameters = method.getParameters();
       for (SQLExpr expr : parameters) {
           if (expr instanceof SQLCharExpr) {
               if (instance.value == null) {
                   instance.value = ((SQLCharExpr) expr).getText();
               } else {
                   instance.analysis = ((SQLCharExpr) expr).getText();
               }
           } else if (expr instanceof SQLNumericLiteralExpr) {
               instance.boost = ((SQLNumericLiteralExpr) expr).getNumber().floatValue();
           } else if (expr instanceof SQLBinaryOpExpr) {
               SQLBinaryOpExpr sqlExpr = (SQLBinaryOpExpr) expr;
               switch (Util.expr2Object(sqlExpr.getLeft()).toString()) {
                   case "query":
                       instance.value = Util.expr2Object(sqlExpr.getRight()).toString();
                       break;
                   case "analyzer":
                       instance.analysis = Util.expr2Object(sqlExpr.getRight()).toString();
                       break;
                   case "boost":
                       instance.boost = Float.parseFloat(Util.expr2Object(sqlExpr.getRight()).toString());
                       break;
                   case "slop":
                       instance.slop = Integer.parseInt(Util.expr2Object(sqlExpr.getRight()).toString());
                       break;

                   case "fields":
                       int index;
                       for (String f : Strings.splitStringByCommaToArray(Util.expr2Object(sqlExpr.getRight()).toString())) {
                           index = f.lastIndexOf('^');
                           if (-1 < index) {
                               instance.fieldsBoosts.put(f.substring(0, index), Float.parseFloat(f.substring(index + 1)));
                           } else {
                               instance.fieldsBoosts.put(f, 1.0F);
                           }
                       }
                       break;
                   case "type":
                       instance.type = Util.expr2Object(sqlExpr.getRight()).toString();
                       break;
                   case "tie_breaker":
                       instance.tieBreaker = Float.parseFloat(Util.expr2Object(sqlExpr.getRight()).toString());
                       break;
                   case "operator":
                       instance.operator = Operator.fromString(Util.expr2Object(sqlExpr.getRight()).toString());
                       break;

                   case "default_field":
                       instance.defaultField = Util.expr2Object(sqlExpr.getRight()).toString();
                       break;

                   case "in_order":
                       instance.inOrder = Boolean.valueOf(Util.expr2Object(sqlExpr.getRight()).toString());
                       break;
                   case "clauses":
                       instance.clauses = Util.expr2Object(sqlExpr.getRight()).toString();
                       break;
                   case "minimum_should_match":
                       instance.minimumShouldMatch = Util.expr2Object(sqlExpr.getRight()).toString();
                       break;

                   default:
                       break;
               }
           }
       }

	return instance;
}