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

The following examples show how to use org.elasticsearch.index.query.QueryBuilders#prefixQuery() . 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: PrefixApiMain.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{
        PrefixQueryBuilder matchQueryBuilder = QueryBuilders.prefixQuery("cmd","get_fee");//查询某个字段存在的记录

        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 2
Source File: NameValue.java    From conductor with Apache License 2.0 6 votes vote down vote up
@Override
public QueryBuilder getFilterBuilder() {
    if (op.getOperator().equals(Operators.EQUALS.value())) {
        return QueryBuilders.queryStringQuery(name.getName() + ":" + value.getValue().toString());
    } else if (op.getOperator().equals(Operators.BETWEEN.value())) {
        return QueryBuilders.rangeQuery(name.getName()).from(range.getLow()).to(range.getHigh());
    } else if (op.getOperator().equals(Operators.IN.value())) {
        return QueryBuilders.termsQuery(name.getName(), valueList.getList());
    } else if (op.getOperator().equals(Operators.NOT_EQUALS.value())) {
        return QueryBuilders.queryStringQuery("NOT " + name.getName() + ":" + value.getValue().toString());
    } else if (op.getOperator().equals(Operators.GREATER_THAN.value())) {
        return QueryBuilders.rangeQuery(name.getName()).from(value.getValue()).includeLower(false).includeUpper(false);
    } else if (op.getOperator().equals(Operators.IS.value())) {
        if (value.getSysConstant().equals(ConstValue.SystemConsts.NULL)) {
            return QueryBuilders.boolQuery().mustNot(QueryBuilders.boolQuery().must(QueryBuilders.matchAllQuery()).mustNot(QueryBuilders.existsQuery(name.getName())));
        } else if (value.getSysConstant().equals(ConstValue.SystemConsts.NOT_NULL)) {
            return QueryBuilders.boolQuery().mustNot(QueryBuilders.boolQuery().must(QueryBuilders.matchAllQuery()).must(QueryBuilders.existsQuery(name.getName())));
        }
    } else if (op.getOperator().equals(Operators.LESS_THAN.value())) {
        return QueryBuilders.rangeQuery(name.getName()).to(value.getValue()).includeLower(false).includeUpper(false);
    } else if (op.getOperator().equals(Operators.STARTS_WITH.value())) {
        return QueryBuilders.prefixQuery(name.getName(), value.getUnquotedValue());
    }

    throw new IllegalStateException("Incorrect/unsupported operators");
}
 
Example 3
Source File: NameValue.java    From conductor with Apache License 2.0 6 votes vote down vote up
@Override
public QueryBuilder getFilterBuilder() {
    if (op.getOperator().equals(Operators.EQUALS.value())) {
        return QueryBuilders.queryStringQuery(name.getName() + ":" + value.getValue().toString());
    } else if (op.getOperator().equals(Operators.BETWEEN.value())) {
        return QueryBuilders.rangeQuery(name.getName()).from(range.getLow()).to(range.getHigh());
    } else if (op.getOperator().equals(Operators.IN.value())) {
        return QueryBuilders.termsQuery(name.getName(), valueList.getList());
    } else if (op.getOperator().equals(Operators.NOT_EQUALS.value())) {
        return QueryBuilders.queryStringQuery("NOT " + name.getName() + ":" + value.getValue().toString());
    } else if (op.getOperator().equals(Operators.GREATER_THAN.value())) {
        return QueryBuilders.rangeQuery(name.getName()).from(value.getValue()).includeLower(false).includeUpper(false);
    } else if (op.getOperator().equals(Operators.IS.value())) {
        if (value.getSysConstant().equals(ConstValue.SystemConsts.NULL)) {
            return QueryBuilders.boolQuery().mustNot(QueryBuilders.boolQuery().must(QueryBuilders.matchAllQuery()).mustNot(QueryBuilders.existsQuery(name.getName())));
        } else if (value.getSysConstant().equals(ConstValue.SystemConsts.NOT_NULL)) {
            return QueryBuilders.boolQuery().mustNot(QueryBuilders.boolQuery().must(QueryBuilders.matchAllQuery()).must(QueryBuilders.existsQuery(name.getName())));
        }
    } else if (op.getOperator().equals(Operators.LESS_THAN.value())) {
        return QueryBuilders.rangeQuery(name.getName()).to(value.getValue()).includeLower(false).includeUpper(false);
    } else if (op.getOperator().equals(Operators.STARTS_WITH.value())) {
        return QueryBuilders.prefixQuery(name.getName(), value.getUnquotedValue());
    }

    throw new IllegalStateException("Incorrect/unsupported operators");
}
 
Example 4
Source File: EsQueryBuilder.java    From es-service-parent with Apache License 2.0 6 votes vote down vote up
/**
 * 前缀查询
 * 
 * @param boolQ
 * @param conditions
 * @param conditionType
 */
private void doPrefix(BoolQueryBuilder boolQ, List<Condition> conditions,
        ConditionType conditionType) {
    QueryBuilder prefix;
    BoolQueryBuilder subBoolQ;
    for (Condition condition : conditions) {
        if (condition.isSpaceSplit()) {
            subBoolQ = QueryBuilders.boolQuery();
            for (String word : KeyWordUtil.processKeyWord(condition.getValue())) {
                subBoolQ.should(QueryBuilders.prefixQuery(condition.getFiled(), word));
            }
            prefix = subBoolQ;
        } else {
            prefix = QueryBuilders.prefixQuery(condition.getFiled(), condition.getValue());
        }
        mergeBuilder(boolQ, prefix, conditionType);
    }
}
 
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: ElasticSearchHelper.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
/**
 * This method create lexical query with boosts if any provided
 *
 * @param key for search
 * @param rangeOperation to search or match in a particular way
 * @param boost for increasing the search parameters priority
 * @return QueryBuilder
 */
public static QueryBuilder createLexicalQuery(
    String key, Map<String, Object> rangeOperation, Float boost) {
  QueryBuilder queryBuilder = null;
  for (Map.Entry<String, Object> it : rangeOperation.entrySet()) {
    switch (it.getKey()) {
      case STARTS_WITH:
        {
          String startsWithVal = (String) it.getValue();
          if (StringUtils.isNotBlank(startsWithVal)) {
            startsWithVal = startsWithVal.toLowerCase();
          }
          if (isNotNull(boost)) {
            queryBuilder =
                QueryBuilders.prefixQuery(key + RAW_APPEND, startsWithVal).boost(boost);
          }
          queryBuilder = QueryBuilders.prefixQuery(key + RAW_APPEND, startsWithVal);
          break;
        }
      case ENDS_WITH:
        {
          String endsWithRegex = "~" + it.getValue();
          if (isNotNull(boost)) {
            queryBuilder =
                QueryBuilders.regexpQuery(key + RAW_APPEND, endsWithRegex).boost(boost);
          }
          queryBuilder = QueryBuilders.regexpQuery(key + RAW_APPEND, endsWithRegex);
          break;
        }
    }
  }
  return queryBuilder;
}
 
Example 7
Source File: PrefixQueryDemo.java    From elasticsearch-full with Apache License 2.0 5 votes vote down vote up
@Test
public void testForClient() throws Exception {
    QueryBuilder qb = QueryBuilders.prefixQuery(
            "brand",
            "heine"
    );
    client.prepareSearch().setQuery(qb).execute().actionGet();
}
 
Example 8
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 9
Source File: SearchService.java    From openvsx with Eclipse Public License 2.0 4 votes vote down vote up
public Page<ExtensionSearch> search(String queryString, String category, Pageable pageRequest, String sortOrder, String sortBy) {
    var queryBuilder = new NativeSearchQueryBuilder()
            .withIndices("extensions")
            .withPageable(pageRequest);
    if (!Strings.isNullOrEmpty(queryString)) {
        var boolQuery = QueryBuilders.boolQuery();

        // Fuzzy matching of search query in multiple fields
        var multiMatchQuery = QueryBuilders.multiMatchQuery(queryString)
                .field("name").boost(5)
                .field("displayName").boost(5)
                .field("tags").boost(3)
                .field("namespace").boost(2)
                .field("description")
                .fuzziness(Fuzziness.AUTO)
                .prefixLength(2);
        boolQuery.should(multiMatchQuery).boost(5);

        // Prefix matching of search query in display name and namespace
        var prefixString = queryString.trim().toLowerCase();
        var namePrefixQuery = QueryBuilders.prefixQuery("displayName", prefixString);
        boolQuery.should(namePrefixQuery).boost(2);
        var namespacePrefixQuery = QueryBuilders.prefixQuery("namespace", prefixString);
        boolQuery.should(namespacePrefixQuery);

        queryBuilder.withQuery(boolQuery);
    }

    if (!Strings.isNullOrEmpty(category)) {
        // Filter by selected category
        queryBuilder.withFilter(QueryBuilders.matchPhraseQuery("categories", category));
    }

    if (!"asc".equalsIgnoreCase(sortOrder) && !"desc".equalsIgnoreCase(sortOrder)) {
        throw new ErrorResultException("sortOrder parameter must be either 'asc' or 'desc'.");
    }

    if ("relevance".equals(sortBy)) {
        queryBuilder.withSort(SortBuilders.scoreSort());
    }

    if ("relevance".equals(sortBy) || "averageRating".equals(sortBy)) {
        queryBuilder.withSort(
                SortBuilders.fieldSort(sortBy).unmappedType("float").order(SortOrder.fromString(sortOrder)));
    } else if ("timestamp".equals(sortBy)) {
        queryBuilder.withSort(
                SortBuilders.fieldSort(sortBy).unmappedType("long").order(SortOrder.fromString(sortOrder)));
    } else if ("downloadCount".equals(sortBy)) {
        queryBuilder.withSort(
                SortBuilders.fieldSort(sortBy).unmappedType("integer").order(SortOrder.fromString(sortOrder)));
    } else {
        throw new ErrorResultException(
                "sortBy parameter must be 'relevance', 'timestamp', 'averageRating' or 'downloadCount'");
    }
    
    try {
        rwLock.readLock().lock();
        return searchOperations.queryForPage(queryBuilder.build(), ExtensionSearch.class);
    } finally {
        rwLock.readLock().unlock();
    }
}
 
Example 10
Source File: IndexingHelper.java    From fess with Apache License 2.0 4 votes vote down vote up
public List<Map<String, Object>> getDocumentListByPrefixId(final FessEsClient fessEsClient, final String id, final String[] fields) {
    final FessConfig fessConfig = ComponentUtil.getFessConfig();
    final QueryBuilder queryBuilder = QueryBuilders.prefixQuery(fessConfig.getIndexFieldId(), id);
    return getDocumentListByQuery(fessEsClient, queryBuilder, fields);
}
 
Example 11
Source File: EsAbstractConditionQuery.java    From fess with Apache License 2.0 4 votes vote down vote up
protected PrefixQueryBuilder regPrefixQ(String name, String prefix) {
    checkEsInvalidQuery(name, prefix);
    PrefixQueryBuilder prefixQuery = QueryBuilders.prefixQuery(name, prefix);
    regQ(prefixQuery);
    return prefixQuery;
}
 
Example 12
Source File: EsAbstractConditionQuery.java    From fess with Apache License 2.0 4 votes vote down vote up
protected PrefixQueryBuilder regPrefixQ(String name, String prefix) {
    checkEsInvalidQuery(name, prefix);
    PrefixQueryBuilder prefixQuery = QueryBuilders.prefixQuery(name, prefix);
    regQ(prefixQuery);
    return prefixQuery;
}
 
Example 13
Source File: EsAbstractConditionQuery.java    From fess with Apache License 2.0 4 votes vote down vote up
protected PrefixQueryBuilder regPrefixQ(String name, String prefix) {
    checkEsInvalidQuery(name, prefix);
    PrefixQueryBuilder prefixQuery = QueryBuilders.prefixQuery(name, prefix);
    regQ(prefixQuery);
    return prefixQuery;
}