Java Code Examples for org.elasticsearch.index.query.QueryBuilders#matchQuery()
The following examples show how to use
org.elasticsearch.index.query.QueryBuilders#matchQuery() .
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: Select.java From code with Apache License 2.0 | 7 votes |
/** * 布尔与词条查询 * 语法: * QueryBuilders:查询构建器工厂 * BoolQueryBuilder:布尔查询构建器 * TermQueryBuilder:词条查询构建器 * 示例: * 查询名称包含手机的,并且品牌为小米的记录 */ @Test public void test2() throws IOException { //2.封装查询请求 SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); // 布尔查询构建器 BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", "手机"); // 词条查询构建器 TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("brandName", "小米"); boolQueryBuilder.must(matchQueryBuilder); boolQueryBuilder.must(termQueryBuilder); searchSourceBuilder.query(boolQueryBuilder); searchRequest.source(searchSourceBuilder); }
Example 2
Source File: StatsAggregationMain.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.matchQuery("cmd", "weather_hourforcast"); StatsAggregationBuilder aggregationBuilder = AggregationBuilders.stats("utm_stats").field("utm").missing(0); SearchRequest searchRequest = new SearchRequest("serverlog_20180710");//限定index searchRequest.types("log");//限定type SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(matchQueryBuilder); searchSourceBuilder.aggregation(aggregationBuilder); searchSourceBuilder.size(0); searchRequest.source(searchSourceBuilder); SearchResponse searchResponse = client.search(searchRequest); System.out.println(searchResponse); }finally{ HighLevelClient.close(); } }
Example 3
Source File: PercentilesAggregationMain.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.matchQuery("cmd", "weather_hourforcast"); PercentilesAggregationBuilder aggregationBuilder = AggregationBuilders.percentiles("utm").field("utm").keyed(false); // PercentilesAggregationBuilder aggregationBuilder = AggregationBuilders.percentiles("utm").field("utm").percentiles(95,99,99.9).keyed(false);//自定义百分区间 SearchRequest searchRequest = new SearchRequest("serverlog_20180710");//限定index searchRequest.types("log");//限定type SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(matchQueryBuilder); searchSourceBuilder.aggregation(aggregationBuilder); searchSourceBuilder.size(0); searchRequest.source(searchSourceBuilder); SearchResponse searchResponse = client.search(searchRequest); System.out.println(searchResponse); }finally{ HighLevelClient.close(); } }
Example 4
Source File: QueryClauseSearchGeneratorTest.java From molgenis with GNU Lesser General Public License v3.0 | 6 votes |
@Test void mapQueryRuleAttributeSearch() { QueryRule queryRule = mock(QueryRule.class); when(queryRule.getField()).thenReturn("attr"); when(queryRule.getValue()).thenReturn("val"); Attribute attribute = mock(Attribute.class); when(attribute.getDataType()).thenReturn(STRING); when(documentIdGenerator.generateId(attribute)).thenReturn("attr"); EntityType entityType = mock(EntityType.class); when(entityType.getAttributeByName("attr")).thenReturn(attribute); QueryBuilder queryBuilder = queryClauseSearchGenerator.mapQueryRule(queryRule, entityType); QueryBuilder expectedQueryBuilder = QueryBuilders.matchQuery("attr", "val"); assertQueryBuilderEquals(expectedQueryBuilder, queryBuilder); }
Example 5
Source File: CountAggregationMain.java From elasticsearch-pool with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws IOException { RestHighLevelClient client = HighLevelClient.getInstance(); try{ QueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("cmd", "get_fee_transfer_content_data"); ValueCountAggregationBuilder aggregationBuilder = AggregationBuilders.count("cmd_count").field("cmd"); SearchRequest searchRequest = new SearchRequest("serverlog_20180715");//限定index searchRequest.types("log");//限定type SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(matchQueryBuilder); searchSourceBuilder.aggregation(aggregationBuilder); searchSourceBuilder.size(0);//不返回具体业务数据,只需要聚合结果 searchRequest.source(searchSourceBuilder); SearchResponse searchResponse = client.search(searchRequest); System.out.println(searchResponse); //统计结果 Aggregations aggregations = searchResponse.getAggregations(); Map<String, Aggregation> aggregationMap = aggregations.asMap(); for(Map.Entry<String,Aggregation> each: aggregationMap.entrySet()){ System.out.println(((ParsedValueCount)(each.getValue())).getValue()); } }finally{ HighLevelClient.close(); } }
Example 6
Source File: FunctionScoreQueryDemo.java From elasticsearch-full with Apache License 2.0 | 5 votes |
@Test public void testForClient() throws Exception { FunctionScoreQueryBuilder.FilterFunctionBuilder[] functions = { new FunctionScoreQueryBuilder.FilterFunctionBuilder( QueryBuilders.matchQuery("name", "kimchy"), ScoreFunctionBuilders. randomFunction()), new FunctionScoreQueryBuilder.FilterFunctionBuilder( ScoreFunctionBuilders.exponentialDecayFunction("age", 0L, 1L)) }; QueryBuilder qb = QueryBuilders.functionScoreQuery(functions); client.prepareSearch().setQuery(qb).execute().actionGet(); }
Example 7
Source File: MatchQueryFunction.java From presto-connectors with Apache License 2.0 | 5 votes |
@ScalarFunction("match_query") @Description("es match_query") @SqlType(StandardTypes.VARCHAR) @SqlNullable public static Slice matchQuery( @SqlType(StandardTypes.VARCHAR) Slice filter) { if (filter == null) { return null; } String filterStr = filter.toStringUtf8(); QueryBuilder builder = QueryBuilders.matchQuery(MATCH_COLUMN_SEP, filterStr); return Slices.utf8Slice(builder.toString()); }
Example 8
Source File: MatchQueryFunction.java From presto-connectors with Apache License 2.0 | 5 votes |
@ScalarFunction("match_query") @Description("es match_query") @SqlType(StandardTypes.VARCHAR) @SqlNullable public static Slice matchQuery( @SqlType(StandardTypes.VARCHAR) Slice filter) { if (filter == null) { return null; } String filterStr = filter.toStringUtf8(); QueryBuilder builder = QueryBuilders.matchQuery(MATCH_COLUMN_SEP, filterStr); return Slices.utf8Slice(builder.toString()); }
Example 9
Source File: MatchQueryFunction.java From presto-connectors with Apache License 2.0 | 5 votes |
@ScalarFunction("match_query") @Description("es match_query") @SqlType(StandardTypes.VARCHAR) @SqlNullable public static Slice matchQuery( @SqlType(StandardTypes.VARCHAR) Slice filter) { if (filter == null) { return null; } String filterStr = filter.toStringUtf8(); QueryBuilder builder = QueryBuilders.matchQuery(MATCH_COLUMN_SEP, filterStr); return Slices.utf8Slice(builder.toString()); }
Example 10
Source File: ElasticsearchUtilTest.java From adaptive-alerting with Apache License 2.0 | 5 votes |
@SneakyThrows @Test public void testGetSourceBuilder() { val queryBuilder = QueryBuilders.matchQuery("createdBy", "kashah"); val actualSourceBuilder = elasticsearchUtil.getSourceBuilder(queryBuilder); assertNotNull(actualSourceBuilder); assertEquals(SearchSourceBuilder.class, actualSourceBuilder.getClass()); }
Example 11
Source File: PersonRepositoryTest.java From spring-boot-demo with MIT License | 5 votes |
/** * 高级查询 */ @Test public void advanceSelect() { // QueryBuilders 提供了很多静态方法,可以实现大部分查询条件的封装 MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("name", "孙权"); log.info("【queryBuilder】= {}", queryBuilder.toString()); repo.search(queryBuilder).forEach(person -> log.info("【person】= {}", person)); }
Example 12
Source File: SearchApiMain.java From elasticsearch-pool with Apache License 2.0 | 4 votes |
public static void searchApi() throws IOException { RestHighLevelClient client = HighLevelClient.getInstance(); try { SearchRequest searchRequest = new SearchRequest("jingma2_test");//限定index searchRequest.types("testlog");//限定type SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); /*查询所有记录*/ // searchSourceBuilder.query(QueryBuilders.matchAllQuery()); /*根据匹配查询*/ QueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", "风雷"); /*设置中文分词器*/ // ((MatchQueryBuilder) matchQueryBuilder).analyzer("ik"); // ((MatchQueryBuilder) matchQueryBuilder).analyzer("ik_max_word"); // ((MatchQueryBuilder) matchQueryBuilder).analyzer("ik_smart"); // ((MatchQueryBuilder) matchQueryBuilder).analyzer("standard"); searchSourceBuilder.query(matchQueryBuilder); /*限定查询条件和查询条数*/ // searchSourceBuilder.query(QueryBuilders.termQuery("name", "风雷")); searchSourceBuilder.from(0); searchSourceBuilder.size(5); // searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS)); /*限定查询结果排序*/ // searchSourceBuilder.sort(new ScoreSortBuilder().order(SortOrder.DESC)); // searchSourceBuilder.sort(new FieldSortBuilder("age").order(SortOrder.ASC)); searchRequest.source(searchSourceBuilder); SearchResponse searchResponse = client.search(searchRequest); System.out.println(searchResponse); SearchHits hits = searchResponse.getHits(); long totalHits = hits.getTotalHits(); float maxScore = hits.getMaxScore(); SearchHit[] searchHits = hits.getHits(); for (SearchHit hit : searchHits) { String index = hit.getIndex(); String type = hit.getType(); String id = hit.getId(); float score = hit.getScore(); String sourceAsString = hit.getSourceAsString(); System.out.println(sourceAsString); // Map<String, Object> sourceAsMap = hit.getSourceAsMap(); } }finally { HighLevelClient.close(); } }
Example 13
Source File: SearchConditionBuilder.java From search-spring-boot-starter with Apache License 2.0 | 4 votes |
/** * 根据查询条件,构建基础查询 * * @param condition 查询条件 * @return 基础查询 */ public QueryBuilder builder(SearchCondition condition, IndexHelper helper) { String fieldName = condition.getFieldName(); final Object singleValue = condition.getSingleValue(); final boolean multipleValue = condition.getMultipleValue(); final ConditionExpressionEnum expression = condition.getConditionExpression(); QueryBuilder queryBuilder; switch (expression) { case EQUAL: fieldName = getFieldName(helper, fieldName, singleValue); queryBuilder = QueryBuilders.termQuery(fieldName, singleValue); break; case LESSER: queryBuilder = QueryBuilders.rangeQuery(fieldName).lt(singleValue); break; case GREATER: queryBuilder = QueryBuilders.rangeQuery(fieldName).gt(singleValue); break; case LESSER_OR_EQUAL: queryBuilder = QueryBuilders.rangeQuery(fieldName).lte(singleValue); break; case GREATER_OR_EQUAL: queryBuilder = QueryBuilders.rangeQuery(fieldName).gte(singleValue); break; case UNEQUAL: fieldName = getFieldName(helper, fieldName, singleValue); queryBuilder = QueryBuilders.boolQuery().mustNot(QueryBuilders.termQuery(fieldName, singleValue)); break; case LIKE: fieldName = getFieldName(helper, fieldName, singleValue); queryBuilder = QueryBuilders.wildcardQuery(fieldName, "*" + singleValue + "*"); break; case NULL: queryBuilder = QueryBuilders.boolQuery().mustNot(QueryBuilders.existsQuery(fieldName)); break; case NOT_NULL: queryBuilder = QueryBuilders.existsQuery(fieldName); break; case IN: fieldName = getFieldName(helper, fieldName, condition.getFieldValues()); queryBuilder = QueryBuilders.termsQuery(fieldName, condition.getFieldValues()); break; case NOT_IN: fieldName = getFieldName(helper, fieldName, condition.getFieldValues()); queryBuilder = QueryBuilders.boolQuery().mustNot(QueryBuilders.termsQuery(fieldName, condition.getFieldValues())); break; case BETWEEN: queryBuilder = QueryBuilders.boolQuery() .must(QueryBuilders.rangeQuery(fieldName).gt(condition.getMinValue()).lt(condition.getMaxValue())); break; case BETWEEN_AND: queryBuilder = QueryBuilders.boolQuery() .must(QueryBuilders.rangeQuery(fieldName).gte(condition.getMinValue()).lte(condition.getMaxValue())); break; case BETWEEN_LEFT: queryBuilder = QueryBuilders.boolQuery() .must(QueryBuilders.rangeQuery(fieldName).gte(condition.getMinValue()).lt(condition.getMaxValue())); break; case BETWEEN_RIGHR: queryBuilder = QueryBuilders.boolQuery() .must(QueryBuilders.rangeQuery(fieldName).gt(condition.getMinValue()).lte(condition.getMaxValue())); break; case MATCH: queryBuilder = QueryBuilders.matchQuery(fieldName, singleValue); break; default: throw new RuntimeException("表达不存在"); } // 若是多值字段,需使用nestedQuery保证查询结果的准确性 if (multipleValue) { if (fieldName.contains(".")) { fieldName = fieldName.substring(0, fieldName.lastIndexOf(".")); } queryBuilder = QueryBuilders.nestedQuery(fieldName, queryBuilder, ScoreMode.None); } return queryBuilder; }
Example 14
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; }
Example 15
Source File: EsAbstractConditionQuery.java From fess with Apache License 2.0 | 4 votes |
protected MatchQueryBuilder regMatchQ(String name, Object value) { checkEsInvalidQuery(name, value); MatchQueryBuilder matchQuery = QueryBuilders.matchQuery(name, value); regQ(matchQuery); return matchQuery; }
Example 16
Source File: ElasticsearchAnySearchDAO.java From syncope with Apache License 2.0 | 4 votes |
private static QueryBuilder fillAttrQuery( final PlainSchema schema, final PlainAttrValue attrValue, final AttrCond cond) { Object value = schema.getType() == AttrSchemaType.Date && attrValue.getDateValue() != null ? attrValue.getDateValue().getTime() : attrValue.getValue(); QueryBuilder builder = EMPTY_QUERY_BUILDER; switch (cond.getType()) { case ISNOTNULL: builder = QueryBuilders.existsQuery(schema.getKey()); break; case ISNULL: builder = QueryBuilders.boolQuery().mustNot(QueryBuilders.existsQuery(schema.getKey())); break; case ILIKE: StringBuilder output = new StringBuilder(); for (char c : cond.getExpression().toLowerCase().toCharArray()) { if (c == '%') { output.append(".*"); } else if (Character.isLetter(c)) { output.append('['). append(c). append(Character.toUpperCase(c)). append(']'); } else { output.append(c); } } builder = QueryBuilders.regexpQuery(schema.getKey(), output.toString()); break; case LIKE: builder = QueryBuilders.wildcardQuery(schema.getKey(), cond.getExpression().replace('%', '*')); break; case IEQ: builder = QueryBuilders.matchQuery(schema.getKey(), cond.getExpression().toLowerCase()); break; case EQ: builder = QueryBuilders.termQuery(schema.getKey(), value); break; case GE: builder = QueryBuilders.rangeQuery(schema.getKey()).gte(value); break; case GT: builder = QueryBuilders.rangeQuery(schema.getKey()).gt(value); break; case LE: builder = QueryBuilders.rangeQuery(schema.getKey()).lte(value); break; case LT: builder = QueryBuilders.rangeQuery(schema.getKey()).lt(value); break; default: } return builder; }
Example 17
Source File: EsAbstractConditionQuery.java From fess with Apache License 2.0 | 4 votes |
protected MatchQueryBuilder regMatchQ(String name, Object value) { checkEsInvalidQuery(name, value); MatchQueryBuilder matchQuery = QueryBuilders.matchQuery(name, value); regQ(matchQuery); return matchQuery; }
Example 18
Source File: ESQueryBuilder.java From search-spring-boot-starter with Apache License 2.0 | 4 votes |
public static ESQueryBuilder match(String name, Object value) { QueryBuilder builder = QueryBuilders.matchQuery(name, value); return new ESQueryBuilder(builder); }
Example 19
Source File: Select.java From code with Apache License 2.0 | 3 votes |
/** * 匹配查询 * 语法: * SearchRequest: 查询请求对象 * SearchResponse:查询响应对象 * SearchSourceBuilder:查询源构建器 * MatchQueryBuilder:匹配查询构建器 * 示例: * 查询商品名称包含手机的记录。 */ @Test public void test1() throws IOException { SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", "小米电视"); searchSourceBuilder.query(matchQueryBuilder); searchRequest.source(searchSourceBuilder); }
Example 20
Source File: ElasticSearchHelper.java From sunbird-lms-service with MIT License | 3 votes |
/** * This method return MatchQueryBuilder Object with boosts if any provided * * @param name of the attribute * @param value of the attribute * @param boost for increasing the search parameters priority * @return MatchQueryBuilder */ public static MatchQueryBuilder createMatchQuery(String name, Object value, Float boost) { if (isNotNull(boost)) { return QueryBuilders.matchQuery(name, value).boost(boost); } else { return QueryBuilders.matchQuery(name, value); } }