Java Code Examples for org.elasticsearch.index.query.QueryBuilders#multiMatchQuery()
The following examples show how to use
org.elasticsearch.index.query.QueryBuilders#multiMatchQuery() .
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: MultiMatchQueryParser.java From elasticsearch-sql with MIT License | 6 votes |
@Override public AtomicQuery parse(ElasticsearchParser.MultiMatchClauseContext expression) { String[] fields=new String[expression.nameClause().size()]; Set<String> highlighters=new HashSet<>(0); for(int i=0;i<expression.nameClause().size();i++){ if(expression.nameClause(i) instanceof ElasticsearchParser.FieldNameContext){ ElasticsearchParser.FieldNameContext fieldNameContext=(ElasticsearchParser.FieldNameContext)expression.nameClause(i); if(fieldNameContext.highlighter!=null){ highlighters.add(fieldNameContext.field.getText()); } fields[i]=fieldNameContext.field.getText(); } } String value = StringManager.removeStringSymbol(expression.value.getText()); AtomicQuery atomicQuery= new AtomicQuery(QueryBuilders.multiMatchQuery(value,fields)); atomicQuery.getHighlighter().addAll(highlighters); return atomicQuery; }
Example 2
Source File: MultiMatchQueryApidMain.java From elasticsearch-pool with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws IOException { RestHighLevelClient client = HighLevelClient.getInstance(); try{ QueryBuilder matchQueryBuilder = QueryBuilders.multiMatchQuery("token","retdesc", "reqpkg");//查询有问题?? SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(matchQueryBuilder); searchSourceBuilder.from(0); searchSourceBuilder.size(5); SearchRequest searchRequest = new SearchRequest("serverlog_20180701");//限定index searchRequest.types("log");//限定type searchRequest.source(searchSourceBuilder); SearchResponse searchResponse = client.search(searchRequest); System.out.println(searchResponse); }finally{ HighLevelClient.close(); } }
Example 3
Source File: HighLevelRestController.java From ProjectStudy with MIT License | 5 votes |
/** * 列表查询 * * @param page * @param rows * @param keyword * @return com.example.common.ResponseBean * @throws * @author wliduo[[email protected]] * @date 2019/8/15 16:01 */ @GetMapping("/book") public ResponseBean list(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer rows, String keyword) throws IOException { SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); // 分页采用简单的from + size分页,适用数据量小的,了解更多分页方式可自行查阅资料 searchSourceBuilder.from((page - 1) * rows); searchSourceBuilder.size(rows); // 查询条件,只有查询关键字不为空才带查询条件 if (StringUtils.isNoneBlank(keyword)) { QueryBuilder queryBuilder = QueryBuilders.multiMatchQuery(keyword, "name", "desc"); searchSourceBuilder.query(queryBuilder); } // 排序,根据ID倒叙 searchSourceBuilder.sort("id", SortOrder.DESC); // SearchRequest SearchRequest searchRequest = new SearchRequest(); searchRequest.source(searchSourceBuilder); // 查询ES SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); SearchHits hits = searchResponse.getHits(); // 获取总数 Long total = hits.getTotalHits().value; // 遍历封装列表对象 List<BookDto> bookDtoList = new ArrayList<>(); SearchHit[] searchHits = hits.getHits(); for (SearchHit searchHit : searchHits) { bookDtoList.add(JSON.parseObject(searchHit.getSourceAsString(), BookDto.class)); } // 封装Map参数返回 Map<String, Object> result = new HashMap<String, Object>(16); result.put("count", total); result.put("data", bookDtoList); return new ResponseBean(HttpStatus.OK.value(), "查询成功", result); }
Example 4
Source File: HighLevelRestController.java From ProjectStudy with MIT License | 5 votes |
/** * 列表查询 * * @param page * @param rows * @param keyword * @return com.example.common.ResponseBean * @throws * @author wliduo[[email protected]] * @date 2019/8/15 16:01 */ @GetMapping("/book") public ResponseBean list(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer rows, String keyword) throws IOException { SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); // 分页采用简单的from + size分页,适用数据量小的,了解更多分页方式可自行查阅资料 searchSourceBuilder.from((page - 1) * rows); searchSourceBuilder.size(rows); // 查询条件,只有查询关键字不为空才带查询条件 if (StringUtils.isNoneBlank(keyword)) { QueryBuilder queryBuilder = QueryBuilders.multiMatchQuery(keyword, "name", "content", "describe"); searchSourceBuilder.query(queryBuilder); } // 排序,根据ID倒叙 // searchSourceBuilder.sort("id", SortOrder.DESC); // 使用unmappedType,解决排序引起的all shards failed问题,详细请自行查阅资料 FieldSortBuilder fieldSortBuilder = SortBuilders.fieldSort("id").order(SortOrder.DESC).unmappedType("text"); searchSourceBuilder.sort(fieldSortBuilder); // SearchRequest SearchRequest searchRequest = new SearchRequest(); searchRequest.source(searchSourceBuilder); // 查询ES SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); SearchHits hits = searchResponse.getHits(); // 获取总数 Long total = hits.getTotalHits().value; // 遍历封装列表对象 List<BookDto> bookDtoList = new ArrayList<>(); SearchHit[] searchHits = hits.getHits(); for (SearchHit searchHit : searchHits) { bookDtoList.add(JSON.parseObject(searchHit.getSourceAsString(), BookDto.class)); } // 封装Map参数返回 Map<String, Object> result = new HashMap<String, Object>(16); result.put("count", total); result.put("data", bookDtoList); return new ResponseBean(HttpStatus.OK.value(), "查询成功", result); }
Example 5
Source File: EsTemplateTest.java From code with Apache License 2.0 | 5 votes |
@Test public void testHighlightQuery() { QueryVO query = new QueryVO(); query.setKeyword("手机"); query.setPage(1); query.setSize(10); // 复合查询 BoolQueryBuilder boolQuery = QueryBuilders.boolQuery(); // 以下为查询条件, 使用 must query 进行查询组合 MultiMatchQueryBuilder matchQuery = QueryBuilders.multiMatchQuery(query.getKeyword(), "title", "category"); boolQuery.must(matchQuery); PageRequest pageRequest = PageRequest.of(query.getPage() - 1, query.getSize()); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder() .withQuery(boolQuery) .withHighlightFields( new HighlightBuilder.Field("title").preTags("<span style=\"color:#F56C6C\">").postTags("</span>"), new HighlightBuilder.Field("category").preTags("<span style=\"color:#F56C6C\">").postTags("</span>")) .withPageable(pageRequest) .build(); Page<Item> items = esTemplate.queryForPage(searchQuery, Item.class, highlightResultMapper); items.forEach(System.out::println); // Item{id=1, title='小米<span style="color:#F56C6C">手机</span>10', category='<span style="color:#F56C6C">手机</span>', // brand='小米', price=3499.0, images='http://image.baidu.com/13123.jpg'} }
Example 6
Source File: MultiMatchQueryDemo.java From elasticsearch-full with Apache License 2.0 | 5 votes |
@Test public void testForClient() throws Exception { /** * @see <a href='https://www.elastic.co/guide/en/elasticsearch/reference/5.6/query-dsl-multi-match-query.html'></a> * MultiMatchQuery依赖于match query ,也就是其核心是基于MatchQuery构建的 * */ MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery("elasticsearch match query","title", "descrption"); multiMatchQueryBuilder.analyzer("standard"); multiMatchQueryBuilder.cutoffFrequency(0.001f); multiMatchQueryBuilder.field("title",20); multiMatchQueryBuilder.fuzziness(Fuzziness.TWO); multiMatchQueryBuilder.maxExpansions(100); multiMatchQueryBuilder.prefixLength(10); multiMatchQueryBuilder.tieBreaker(20); multiMatchQueryBuilder.type(MultiMatchQueryBuilder.Type.BEST_FIELDS); multiMatchQueryBuilder.boost(20); SearchResponse searchResponse = client.prepareSearch() .setIndices("blogs") .setTypes("blog") .setQuery(multiMatchQueryBuilder) .execute() .actionGet(); }
Example 7
Source File: FullTextSearchLookupDescriptor.java From metasfresh-webui-api-legacy with GNU General Public License v3.0 | 4 votes |
private QueryBuilder createElasticsearchQuery(final LookupDataSourceContext evalCtx) { final String text = evalCtx.getFilter(); return QueryBuilders.multiMatchQuery(text, esSearchFieldNames); }
Example 8
Source File: FullTextSearchSqlDocumentFilterConverter.java From metasfresh-webui-api-legacy with GNU General Public License v3.0 | 4 votes |
@Override public String getSql( final SqlParamsCollector sqlParamsOut, final DocumentFilter filter, final SqlOptions sqlOpts, final SqlDocumentFilterConverterContext context) { final String text = filter.getParameterValueAsString(PARAM_SearchText); if (Check.isEmpty(text, true)) { return "1=1"; } final FullTextSearchFilterContext ftsContext = filter.getParameterValueAs(PARAM_Context); Check.assumeNotNull(ftsContext, "Parameter ftsContext is not null"); // shall not happen logger.trace("context: {}", ftsContext); final Client elasticsearchClient = ftsContext.getElasticsearchClient(); final String esIndexName = ftsContext.getEsIndexName(); final String keyColumnName = ftsContext.getKeyColumnName(); final String esKeyColumnName = ftsContext.getEsKeyColumnName(); final QueryBuilder query = QueryBuilders.multiMatchQuery(text, ftsContext.getEsSearchFieldNamesAsArray()); logger.trace("ES query: {}", query); final SearchResponse searchResponse = elasticsearchClient.prepareSearch(esIndexName) .setQuery(query) .setExplain(logger.isTraceEnabled()) .get(); logger.trace("ES response: {}", searchResponse); final List<Integer> recordIds = Stream.of(searchResponse.getHits().getHits()) .map(hit -> extractId(hit, esKeyColumnName)) .filter(id -> id >= 0) .distinct() .collect(ImmutableList.toImmutableList()); logger.trace("Record IDs: {}", recordIds); if (recordIds.isEmpty()) { return "1=0"; } final String keyColumnNameFQ = sqlOpts.getTableNameOrAlias() + "." + keyColumnName; return DB.buildSqlList(keyColumnNameFQ, recordIds, null); }
Example 9
Source File: Maker.java From elasticsearch-sql with Apache License 2.0 | 4 votes |
private ToXContent make(Condition cond, String name, SQLMethodInvokeExpr value) throws SqlParseException { ToXContent bqb = null; Paramer paramer = null; switch (value.getMethodName().toLowerCase()) { case "query": paramer = Paramer.parseParamer(value); QueryStringQueryBuilder queryString = QueryBuilders.queryStringQuery(paramer.value); bqb = Paramer.fullParamer(queryString, paramer); bqb = fixNot(cond, bqb); break; case "matchquery": case "match_query": paramer = Paramer.parseParamer(value); MatchQueryBuilder matchQuery = QueryBuilders.matchQuery(name, paramer.value); bqb = Paramer.fullParamer(matchQuery, paramer); bqb = fixNot(cond, bqb); break; case "score": case "scorequery": case "score_query": float boost = Float.parseFloat(value.getParameters().get(1).toString()); Condition subCond = new Condition(cond.getConn(), cond.getName(),null, cond.getOpear(), value.getParameters().get(0),null); bqb = QueryBuilders.constantScoreQuery((QueryBuilder) make(subCond)).boost(boost); break; case "wildcardquery": case "wildcard_query": paramer = Paramer.parseParamer(value); WildcardQueryBuilder wildcardQuery = QueryBuilders.wildcardQuery(name, paramer.value); bqb = Paramer.fullParamer(wildcardQuery, paramer); break; case "matchphrasequery": case "match_phrase": case "matchphrase": paramer = Paramer.parseParamer(value); MatchPhraseQueryBuilder matchPhraseQuery = QueryBuilders.matchPhraseQuery(name, paramer.value); bqb = Paramer.fullParamer(matchPhraseQuery, paramer); break; case "multimatchquery": case "multi_match": case "multimatch": paramer = Paramer.parseParamer(value); MultiMatchQueryBuilder multiMatchQuery = QueryBuilders.multiMatchQuery(paramer.value); bqb = Paramer.fullParamer(multiMatchQuery, paramer); break; case "spannearquery": case "span_near": case "spannear": paramer = Paramer.parseParamer(value); // parse clauses List<SpanQueryBuilder> clauses = new ArrayList<>(); try (XContentParser parser = JsonXContent.jsonXContent.createParser(new NamedXContentRegistry(new SearchModule(Settings.EMPTY, true, Collections.emptyList()).getNamedXContents()), LoggingDeprecationHandler.INSTANCE, paramer.clauses)) { while (parser.nextToken() != XContentParser.Token.END_ARRAY) { QueryBuilder query = SpanNearQueryBuilder.parseInnerQueryBuilder(parser); if (!(query instanceof SpanQueryBuilder)) { throw new ParsingException(parser.getTokenLocation(), "spanNear [clauses] must be of type span query"); } clauses.add((SpanQueryBuilder) query); } } catch (IOException e) { throw new SqlParseException("could not parse clauses: " + e.getMessage()); } // SpanNearQueryBuilder spanNearQuery = QueryBuilders.spanNearQuery(clauses.get(0), Optional.ofNullable(paramer.slop).orElse(SpanNearQueryBuilder.DEFAULT_SLOP)); for (int i = 1; i < clauses.size(); ++i) { spanNearQuery.addClause(clauses.get(i)); } bqb = Paramer.fullParamer(spanNearQuery, paramer); break; case "matchphraseprefix": case "matchphraseprefixquery": case "match_phrase_prefix": paramer = Paramer.parseParamer(value); MatchPhrasePrefixQueryBuilder phrasePrefixQuery = QueryBuilders.matchPhrasePrefixQuery(name, paramer.value); bqb = Paramer.fullParamer(phrasePrefixQuery, paramer); break; default: throw new SqlParseException("it did not support this query method " + value.getMethodName()); } return bqb; }