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

The following examples show how to use org.elasticsearch.index.query.QueryBuilders#matchPhraseQuery() . 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: MatchPhraseQueryDemo.java    From elasticsearch-full with Apache License 2.0 7 votes vote down vote up
@Test
public void test() throws Exception {
    String key = "this is a";
    MatchPhraseQueryBuilder matchPhraseQueryBuilder = QueryBuilders.matchPhraseQuery("title",key);

    matchPhraseQueryBuilder.boost(10);
    matchPhraseQueryBuilder.analyzer("standard");
    matchPhraseQueryBuilder.slop(2);

       SearchResponse searchResponse = client.prepareSearch()
                .setIndices("my_index")
                .setTypes("my_type")
                .setQuery(matchPhraseQueryBuilder)
                .execute()
                .actionGet();
}
 
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: EsQueryBuilder.java    From es-service-parent with Apache License 2.0 7 votes vote down vote up
/**
 * 短语查询-支持带空格
 * 
 * @param boolQ
 * @param conditions
 * @param conditionType
 */
private void doMatchPhrase(BoolQueryBuilder boolQ, List<Condition> conditions,
        ConditionType conditionType) {
    String filed;
    QueryBuilder match;
    BoolQueryBuilder subBoolQ;
    for (Condition condition : conditions) {
        // 字段名为空则在_all上搜索
        filed = condition.getFiled();
        filed = StringUtils.isBlank(filed) ? "_all" : filed;
        if (condition.isSpaceSplit()) {
            subBoolQ = QueryBuilders.boolQuery();
            for (String word : KeyWordUtil.processKeyWord(condition.getValue())) {
                subBoolQ.should(QueryBuilders.matchPhraseQuery(filed, word));
            }
            match = subBoolQ;
        } else {
            match = QueryBuilders.matchPhraseQuery(filed, condition.getValue());
        }
        mergeBuilder(boolQ, match, conditionType);
    }
}
 
Example 4
Source File: MatchParseApiMain.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{
        QueryBuilder matchQueryBuilder = QueryBuilders.matchPhraseQuery("content","校车");

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

        SearchRequest searchRequest = new SearchRequest("jingma2");//限定index
        searchRequest.types("fulltext");//限定type
        searchRequest.source(searchSourceBuilder);

        SearchResponse searchResponse = client.search(searchRequest);
        System.out.println(searchResponse);


    }finally{
        HighLevelClient.close();
    }
}
 
Example 5
Source File: QueryHelper.java    From fess with Apache License 2.0 6 votes vote down vote up
protected QueryBuilder buildMatchPhraseQuery(final String f, final String text) {
    final FessConfig fessConfig = ComponentUtil.getFessConfig();
    if (text == null || text.length() != 1
            || (!fessConfig.getIndexFieldTitle().equals(f) && !fessConfig.getIndexFieldContent().equals(f))) {
        return QueryBuilders.matchPhraseQuery(f, text);
    }

    final UnicodeBlock block = UnicodeBlock.of(text.codePointAt(0));
    if (block == UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS //
            || block == UnicodeBlock.HIRAGANA //
            || block == UnicodeBlock.KATAKANA //
            || block == UnicodeBlock.HANGUL_SYLLABLES //
    ) {
        return QueryBuilders.prefixQuery(f, text);
    }
    return QueryBuilders.matchPhraseQuery(f, text);
}
 
Example 6
Source File: MatchQueryFunction.java    From presto-connectors with Apache License 2.0 5 votes vote down vote up
@ScalarFunction("match_phrase")
@Description("es match_phrase")
@SqlType(StandardTypes.VARCHAR)
@SqlNullable
public static Slice matchPhrase(
        @SqlType(StandardTypes.VARCHAR) Slice filter)
{
    if (filter == null) {
        return null;
    }
    String filterStr = filter.toStringUtf8();

    QueryBuilder builder = QueryBuilders.matchPhraseQuery(MATCH_COLUMN_SEP, filterStr);
    return Slices.utf8Slice(builder.toString());
}
 
Example 7
Source File: MatchQueryFunction.java    From presto-connectors with Apache License 2.0 5 votes vote down vote up
@ScalarFunction("match_phrase")
@Description("es match_phrase")
@SqlType(StandardTypes.VARCHAR)
@SqlNullable
public static Slice matchPhrase(
        @SqlType(StandardTypes.VARCHAR) Slice filter)
{
    if (filter == null) {
        return null;
    }
    String filterStr = filter.toStringUtf8();

    QueryBuilder builder = QueryBuilders.matchPhraseQuery(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 vote down vote up
@ScalarFunction("match_phrase")
@Description("es match_phrase")
@SqlType(StandardTypes.VARCHAR)
@SqlNullable
public static Slice matchPhrase(
        @SqlType(StandardTypes.VARCHAR) Slice filter)
{
    if (filter == null) {
        return null;
    }
    String filterStr = filter.toStringUtf8();

    QueryBuilder builder = QueryBuilders.matchPhraseQuery(MATCH_COLUMN_SEP, filterStr);
    return Slices.utf8Slice(builder.toString());
}
 
Example 9
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 10
Source File: ElasticSearchUtil.java    From ranger with Apache License 2.0 4 votes vote down vote up
private QueryBuilder getQueryBuilder(SearchField.DATA_TYPE dataType, SearchField.SEARCH_TYPE searchType, String fieldName, Object paramValue) {
    if (paramValue == null || paramValue.toString().isEmpty()) {
        return null;
    }
    if (fieldName.startsWith("-")) {
        QueryBuilder negativeQuery = getQueryBuilder(dataType, searchType, fieldName.substring(1), paramValue);
        return null == negativeQuery ? null : QueryBuilders.boolQuery().mustNot(negativeQuery);
    }
    if (paramValue instanceof Collection) {
        Collection<?> valueList = (Collection<?>) paramValue;
        if (valueList.isEmpty()) {
            return null;
        } else {
            return QueryBuilders.queryStringQuery(valueList.stream()
                    .map(ElasticSearchUtil.this::filterText)
                    .map(x -> "(" + x + ")")
                    .reduce((a, b) -> a + " OR " + b)
                    .get()
            ).defaultField(fieldName);
        }
    } else {
        if (dataType == SearchField.DATA_TYPE.DATE) {
            if (!(paramValue instanceof Date)) {
                logger.error(String.format(
                    "Search value is not a Java Date Object: %s %s %s",
                    fieldName, searchType, paramValue));
            } else {
                if (searchType == SearchField.SEARCH_TYPE.GREATER_EQUAL_THAN
                        || searchType == SearchField.SEARCH_TYPE.GREATER_THAN) {
                    fromDate = (Date) paramValue;
                    dateFieldName = fieldName;
                } else if (searchType == SearchField.SEARCH_TYPE.LESS_EQUAL_THAN
                        || searchType == SearchField.SEARCH_TYPE.LESS_THAN) {
                    toDate = (Date) paramValue;
                    dateFieldName = fieldName;
                }
            }
            return null;
        } else if (searchType == SearchField.SEARCH_TYPE.GREATER_EQUAL_THAN
                || searchType == SearchField.SEARCH_TYPE.GREATER_THAN
                || searchType == SearchField.SEARCH_TYPE.LESS_EQUAL_THAN
                || searchType == SearchField.SEARCH_TYPE.LESS_THAN) { //NOPMD
            logger.warn(String.format("Range Queries Not Implemented: %s %s %s",
                fieldName, searchType, paramValue));
            return null;
        } else {
            if (searchType == SearchField.SEARCH_TYPE.PARTIAL) {
                if (paramValue.toString().trim().length() == 0) {
                    return null;
                } else {
                    return QueryBuilders.queryStringQuery("*" + filterText(paramValue) + "*").defaultField(fieldName);
                }
            } else {
                if (paramValue.toString().trim().length() > 0) {
                    return QueryBuilders.matchPhraseQuery(fieldName, filterText(paramValue));
                } else {
                    return null;
                }
            }
        }
    }
}
 
Example 11
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 12
Source File: EsAbstractConditionQuery.java    From fess with Apache License 2.0 4 votes vote down vote up
protected MatchPhraseQueryBuilder regMatchPhraseQ(String name, Object value) {
    checkEsInvalidQuery(name, value);
    MatchPhraseQueryBuilder matchQuery = QueryBuilders.matchPhraseQuery(name, value);
    regQ(matchQuery);
    return matchQuery;
}
 
Example 13
Source File: EsAbstractConditionQuery.java    From fess with Apache License 2.0 4 votes vote down vote up
protected MatchPhraseQueryBuilder regMatchPhraseQ(String name, Object value) {
    checkEsInvalidQuery(name, value);
    MatchPhraseQueryBuilder matchQuery = QueryBuilders.matchPhraseQuery(name, value);
    regQ(matchQuery);
    return matchQuery;
}
 
Example 14
Source File: EsAbstractConditionQuery.java    From fess with Apache License 2.0 4 votes vote down vote up
protected MatchPhraseQueryBuilder regMatchPhraseQ(String name, Object value) {
    checkEsInvalidQuery(name, value);
    MatchPhraseQueryBuilder matchQuery = QueryBuilders.matchPhraseQuery(name, value);
    regQ(matchQuery);
    return matchQuery;
}