Java Code Examples for org.elasticsearch.index.query.QueryBuilders#wildcardQuery()

The following examples show how to use org.elasticsearch.index.query.QueryBuilders#wildcardQuery() . 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: TestController.java    From SpringBootLearn with Apache License 2.0 7 votes vote down vote up
/**
 * 通配符查询数据
 * 通配符查询 ?用来匹配1个任意字符,*用来匹配零个或者多个字符
 * @return
 */
@GetMapping("/queryWildcardData")
public String queryWildcardData() {
    QueryBuilder queryBuilder = QueryBuilders.wildcardQuery("name.keyword", "书名*2");
    List<Map<String, Object>> list = ElasticsearchUtil.searchListData(indexName, esType, queryBuilder, 10, null, null, null);
    return JSONObject.toJSONString(list);
}
 
Example 2
Source File: WhereParser.java    From sql4es with Apache License 2.0 7 votes vote down vote up
/**
 * Interprets the string term and returns an appropriate Query (wildcard, phrase or term)
 * @param field
 * @param term
 * @return
 */
private QueryBuilder queryForString(String field, String term){
	if(term.contains("%") || term.contains("_")){
		return QueryBuilders.wildcardQuery(field, term.replaceAll("%", "*").replaceAll("_", "?"));
	}else if  (term.contains(" ") ){
		return QueryBuilders.matchPhraseQuery(field, term);
	}else return QueryBuilders.termQuery(field, term);
}
 
Example 3
Source File: EkmKnowledgeMasterRepositoryImpl.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@Override
	public Page<EkmKnowledgeMaster> findByKnowbaseidAndKnowledgetypeidAndDatastatusAndOrgi(String knowbaseid,
			String knowledgetypeid, boolean datastatus, String orgi, BoolQueryBuilder ranyQueryBuilder, Pageable page) {
		
		BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
		boolQueryBuilder.must(termQuery("datastatus" , datastatus)) ;
		boolQueryBuilder.must(termQuery("orgi" ,orgi)) ;
		boolQueryBuilder.must(ranyQueryBuilder) ;
		//boolQueryBuilder.must(termQuery("pubstatus" , UKDataContext.PubStatusEnum.PASS.toString())) ;//审核通过
		if(!StringUtils.isBlank(knowbaseid)){
			boolQueryBuilder.must(termQuery("knowbaseid" , knowbaseid)) ;
		}else{
			boolQueryBuilder.must(termQuery("knowbaseid" , UKDataContext.UKEFU_SYSTEM_NO_DAT)) ;
		}
		if(!StringUtils.isBlank(knowledgetypeid)){
//			boolQueryBuilder.must(termQuery("knowledgetypeid" , knowledgetypeid)) ;
			WildcardQueryBuilder wildcardqueryBuilder = QueryBuilders.wildcardQuery("attr", "*"+knowledgetypeid+"*");
			boolQueryBuilder.must(wildcardqueryBuilder) ;
		}else{
			boolQueryBuilder.must(termQuery("knowledgetypeid" , UKDataContext.UKEFU_SYSTEM_NO_DAT)) ;
		}
		return processQuery(boolQueryBuilder , page);
	}
 
Example 4
Source File: WildcardApiMain.java    From elasticsearch-pool with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {

        RestHighLevelClient client = HighLevelClient.getInstance();
        try{
            WildcardQueryBuilder matchQueryBuilder = QueryBuilders.wildcardQuery("cmd","get_fee*");//cmd必须匹配指定的正则表达式,不能是包含关系

            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(matchQueryBuilder);
            searchSourceBuilder.from(0);
            searchSourceBuilder.size(1);

            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 5
Source File: EsQueryVistor.java    From usergrid with Apache License 2.0 6 votes vote down vote up
@Override
public void visit( ContainsOperand op ) throws NoFullTextIndexException {
    final String name = op.getProperty().getValue().toLowerCase();
    final String value = op.getLiteral().getValue().toString().toLowerCase();


    // or field is just a string that does need a prefix
    if ( value.indexOf( "*" ) != -1 ) {
        final WildcardQueryBuilder wildcardQuery =
                QueryBuilders.wildcardQuery( IndexingUtils.FIELD_STRING_NESTED, value );
        queryBuilders.push( fieldNameTerm( name, wildcardQuery ) );
    }
    else {
        final MatchQueryBuilder termQuery = QueryBuilders.matchQuery( IndexingUtils.FIELD_STRING_NESTED, value );

        queryBuilders.push( fieldNameTerm( name, termQuery ) );
    }


    //no op for filters, push an empty operation

    //TODO, validate this works
    filterBuilders.push( NoOpFilterBuilder.INSTANCE );
}
 
Example 6
Source File: QueryClauseLikeGeneratorTest.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
void mapQueryRuleToken() {
  QueryRule queryRule = mock(QueryRule.class);
  when(queryRule.getField()).thenReturn("attr");
  when(queryRule.getValue()).thenReturn("val");

  Attribute attribute = mock(Attribute.class);
  when(attribute.getDataType()).thenReturn(AttributeType.STRING);
  when(attribute.getTags()).thenReturn(List.of(tokenTag));
  when(tokenTag.equals(RDF.TYPE, XMLSchema.TOKEN)).thenReturn(true);
  when(documentIdGenerator.generateId(attribute)).thenReturn("attr");

  EntityType entityType = mock(EntityType.class);
  when(entityType.getAttributeByName("attr")).thenReturn(attribute);

  QueryBuilder queryBuilder = queryClauseLikeGenerator.mapQueryRule(queryRule, entityType);
  QueryBuilder expectedQueryBuilder = QueryBuilders.wildcardQuery("attr", "*val*");
  assertQueryBuilderEquals(expectedQueryBuilder, queryBuilder);
}
 
Example 7
Source File: AST_Search.java    From elasticsearch-rest-command with The Unlicense 5 votes vote down vote up
private static QueryBuilder fromValueTypeQ(String field, String value, int valueType){
	if(value.contains("*") || value.contains("?")){
		if( value.length() > 1 && value.indexOf('*') == (value.length()-1))
			return QueryBuilders.prefixQuery(field, value.substring(0, value.length()-1));
		else
			return QueryBuilders.wildcardQuery(field, value);
	}else if(value.equalsIgnoreCase("")){
		
		return QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), FilterBuilders.boolFilter()
				.should(FilterBuilders.scriptFilter("doc['"+field+"'].value.size() == 0"))					
				.should(FilterBuilders.missingFilter(field).nullValue(true).existence(true)));
	}
	//全部使用对短语进行分词后再搜索
	return QueryBuilders.matchPhraseQuery(field, value);
	
	
	/*
	switch(valueType){
	
	case AST_TermExpression.TERM:
		return QueryBuilders.termQuery(field, value);
	case AST_TermExpression.PHRASE:			
		return QueryBuilders.matchPhraseQuery(field, value);
	}
	
	
	return null;
	*/
}
 
Example 8
Source File: QueryClauseLikeGenerator.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
private QueryBuilder getQueryBuilder(Attribute attr, String fieldName, Object queryValue) {
  if (isTaggedType(attr, XMLSchema.TOKEN)) {
    return QueryBuilders.wildcardQuery(fieldName, format("*%s*", queryValue));
  } else {
    return QueryBuilders.matchPhrasePrefixQuery(fieldName, queryValue)
        .maxExpansions(50)
        .slop(10)
        .analyzer(DEFAULT_ANALYZER);
  }
}
 
Example 9
Source File: EsQueryVistor.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@Override
public void visit( Equal op ) throws NoIndexException {
    final String name = op.getProperty().getValue().toLowerCase();
    final Object value = op.getLiteral().getValue();

    //special case so we support our '*' char with wildcard, also should work for uuids
    if ( value instanceof String || value instanceof UUID ) {
        String stringValue = ((value instanceof String) ? (String)value : value.toString()).toLowerCase().trim();

        // or field is just a string that does need a prefix us a query
        if ( stringValue.contains( "*" ) ) {

            //Because of our legacy behavior, where we match CCCC*, we need to use the unanalyzed string to ensure that
            //we start
            final WildcardQueryBuilder wildcardQuery =
                    QueryBuilders.wildcardQuery( IndexingUtils.FIELD_STRING_NESTED_UNANALYZED, stringValue );
            queryBuilders.push( fieldNameTerm( name, wildcardQuery ) );
            filterBuilders.push( NoOpFilterBuilder.INSTANCE );
            return;
        }

        // Usergrid query parser allows single quotes to be escaped in values
        if ( stringValue.contains("\\'")) {
            stringValue = stringValue.replace("\\'", "'");
        }

        //it's an exact match, use a filter
        final TermFilterBuilder termFilter =
                FilterBuilders.termFilter( IndexingUtils.FIELD_STRING_NESTED_UNANALYZED, stringValue );

        queryBuilders.push( NoOpQueryBuilder.INSTANCE );
        filterBuilders.push( fieldNameTerm( name, termFilter ) );

        return;
    }

    // assume all other types need prefix

    final TermFilterBuilder termQuery =
            FilterBuilders.termFilter(getFieldNameForType(value), sanitize(value));

    filterBuilders.push( fieldNameTerm( name, termQuery ) );

    queryBuilders.push( NoOpQueryBuilder.INSTANCE );
}
 
Example 10
Source File: EsAbstractConditionQuery.java    From fess with Apache License 2.0 4 votes vote down vote up
protected WildcardQueryBuilder regWildcardQ(String name, String wildcard) {
    checkEsInvalidQuery(name, wildcard);
    WildcardQueryBuilder wildcardQuery = QueryBuilders.wildcardQuery(name, wildcard);
    regQ(wildcardQuery);
    return wildcardQuery;
}
 
Example 11
Source File: EsAbstractConditionQuery.java    From fess with Apache License 2.0 4 votes vote down vote up
protected WildcardQueryBuilder regWildcardQ(String name, String wildcard) {
    checkEsInvalidQuery(name, wildcard);
    WildcardQueryBuilder wildcardQuery = QueryBuilders.wildcardQuery(name, wildcard);
    regQ(wildcardQuery);
    return wildcardQuery;
}
 
Example 12
Source File: EsAbstractConditionQuery.java    From fess with Apache License 2.0 4 votes vote down vote up
protected WildcardQueryBuilder regWildcardQ(String name, String wildcard) {
    checkEsInvalidQuery(name, wildcard);
    WildcardQueryBuilder wildcardQuery = QueryBuilders.wildcardQuery(name, wildcard);
    regQ(wildcardQuery);
    return wildcardQuery;
}
 
Example 13
Source File: ElasticsearchAnySearchDAO.java    From syncope with Apache License 2.0 4 votes vote down vote up
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 14
Source File: Maker.java    From elasticsearch-sql with Apache License 2.0 4 votes vote down vote up
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: WildcardQueryDemo.java    From elasticsearch-full with Apache License 2.0 4 votes vote down vote up
@Test
public void testForClient() throws Exception {
    QueryBuilder qb = QueryBuilders.wildcardQuery("user", "k?mc*");
    client.prepareSearch().setQuery(qb).execute().actionGet();
}
 
Example 16
Source File: SearchController.java    From phoebus with Eclipse Public License 1.0 4 votes vote down vote up
@RequestMapping(value = "/search/alarm/{config}", method = RequestMethod.GET)
public List<AlarmStateMessage> searchConfig(@PathVariable String config) {
    QueryBuilder query = QueryBuilders.wildcardQuery("config", config);
    return esAlarmSearch(query);
}
 
Example 17
Source File: SearchController.java    From phoebus with Eclipse Public License 1.0 4 votes vote down vote up
@RequestMapping(value = "/search/alarm/{pv}", method = RequestMethod.GET)
public List<AlarmStateMessage> searchPv(@PathVariable String pv) {
    QueryBuilder query = QueryBuilders.wildcardQuery("pv", pv);
    return esAlarmSearch(query);
}
 
Example 18
Source File: SearchConditionBuilder.java    From search-spring-boot-starter with Apache License 2.0 4 votes vote down vote up
/**
 * 根据查询条件,构建基础查询
 *
 * @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;
}