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

The following examples show how to use org.elasticsearch.index.query.QueryBuilders#queryStringQuery() . 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: RestActions.java    From Elasticsearch with Apache License 2.0 8 votes vote down vote up
public static QuerySourceBuilder parseQuerySource(RestRequest request) {
    String queryString = request.param("q");
    if (queryString == null) {
        return null;
    }
    QueryStringQueryBuilder queryBuilder = QueryBuilders.queryStringQuery(queryString);
    queryBuilder.defaultField(request.param("df"));
    queryBuilder.analyzer(request.param("analyzer"));
    queryBuilder.analyzeWildcard(request.paramAsBoolean("analyze_wildcard", false));
    queryBuilder.lowercaseExpandedTerms(request.paramAsBoolean("lowercase_expanded_terms", true));
    queryBuilder.lenient(request.paramAsBoolean("lenient", null));
    String defaultOperator = request.param("default_operator");
    if (defaultOperator != null) {
        if ("OR".equals(defaultOperator)) {
            queryBuilder.defaultOperator(QueryStringQueryBuilder.Operator.OR);
        } else if ("AND".equals(defaultOperator)) {
            queryBuilder.defaultOperator(QueryStringQueryBuilder.Operator.AND);
        } else {
            throw new IllegalArgumentException("Unsupported defaultOperator [" + defaultOperator + "], can either be [OR] or [AND]");
        }
    }
    return new QuerySourceBuilder().setQuery(queryBuilder);
}
 
Example 2
Source File: QueryClauseFuzzyMatchNgramGeneratorTest.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
void mapQueryRule() {
  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(documentIdGenerator.generateId(attribute)).thenReturn("attr");

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

  QueryBuilder queryBuilder =
      queryClauseFuzzyMatchNgramGenerator.mapQueryRule(queryRule, entityType);
  QueryBuilder expectedQueryBuilder = QueryBuilders.queryStringQuery("attr.ngram:(val)");
  assertQueryBuilderEquals(expectedQueryBuilder, queryBuilder);
}
 
Example 3
Source File: DecompoundQueryTests.java    From elasticsearch-plugin-bundle with GNU Affero General Public License v3.0 6 votes vote down vote up
public void testNestedCommonPhraseQuery() throws Exception {
    List<IndexRequestBuilder> reqs = new ArrayList<>();
    reqs.add(client().prepareIndex("test", "_doc", "1").setSource("text", "deutsche Spielbankgesellschaft"));
    indexRandom(true, false, reqs);

    QueryStringQueryBuilder queryStringQueryBuilder =
            QueryBuilders.queryStringQuery("text:\"deutsche spielbankgesellschaft\"");
    ExactPhraseQueryBuilder exactPhraseQueryBuilder = new ExactPhraseQueryBuilder(queryStringQueryBuilder);
    SearchResponse resp = client().prepareSearch("test").setQuery(exactPhraseQueryBuilder).get();
    ElasticsearchAssertions.assertHitCount(resp, 1L);
    assertHits(resp.getHits(), "1");

    QueryStringQueryBuilder queryStringQueryBuilder2 =
            QueryBuilders.queryStringQuery("text:\"deutsche bank\"");
    ExactPhraseQueryBuilder exactPhraseQueryBuilder2 = new ExactPhraseQueryBuilder(queryStringQueryBuilder2);
    SearchResponse resp2 = client().prepareSearch("test").setQuery(exactPhraseQueryBuilder2).get();
    ElasticsearchAssertions.assertHitCount(resp2, 0L);

    QueryStringQueryBuilder queryStringQueryBuilder3 =
            QueryBuilders.queryStringQuery("text:\"deutsche spielbankgesellschaft\" AND NOT text:\"deutsche bank\"");
    ExactPhraseQueryBuilder exactPhraseQueryBuilder3 = new ExactPhraseQueryBuilder(queryStringQueryBuilder3);
    SearchResponse resp3 = client().prepareSearch("test").setQuery(exactPhraseQueryBuilder3).get();
    ElasticsearchAssertions.assertHitCount(resp3, 1L);
    assertHits(resp3.getHits(), "1");
}
 
Example 4
Source File: QueryClauseFuzzyMatchGeneratorTest.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
void mapQueryRule() {
  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(documentIdGenerator.generateId(attribute)).thenReturn("attr");

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

  QueryBuilder queryBuilder = queryClauseFuzzyMatchGenerator.mapQueryRule(queryRule, entityType);
  QueryBuilder expectedQueryBuilder = QueryBuilders.queryStringQuery("attr:(val)");
  assertQueryBuilderEquals(expectedQueryBuilder, queryBuilder);
}
 
Example 5
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 6
Source File: TestElasticSearchRestDAOV5.java    From conductor with Apache License 2.0 6 votes vote down vote up
private SearchResponse searchObjectIdsViaExpression(String indexName, String structuredQuery, int start, int size,
                                                    List<String> sortOptions, String freeTextQuery, String docType) throws ParserException, IOException {

    // Build query
    QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
    if(StringUtils.isNotEmpty(structuredQuery)) {
        Expression expression = Expression.fromString(structuredQuery);
        queryBuilder = expression.getFilterBuilder();
    }

    BoolQueryBuilder filterQuery = QueryBuilders.boolQuery().must(queryBuilder);
    QueryStringQueryBuilder stringQuery = QueryBuilders.queryStringQuery(freeTextQuery);
    BoolQueryBuilder fq = QueryBuilders.boolQuery().must(stringQuery).must(filterQuery);

    return searchObjectIds(indexName, fq, start, size, sortOptions, docType);
}
 
Example 7
Source File: TestElasticSearchDAOV5.java    From conductor with Apache License 2.0 6 votes vote down vote up
private SearchResponse search(String indexName, String structuredQuery, int start,
    int size, String freeTextQuery, String docType) throws ParserException {
    QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
    if (StringUtils.isNotEmpty(structuredQuery)) {
        Expression expression = Expression.fromString(structuredQuery);
        queryBuilder = expression.getFilterBuilder();
    }

    BoolQueryBuilder filterQuery = QueryBuilders.boolQuery().must(queryBuilder);
    QueryStringQueryBuilder stringQuery = QueryBuilders.queryStringQuery(freeTextQuery);
    BoolQueryBuilder fq = QueryBuilders.boolQuery().must(stringQuery).must(filterQuery);
    final SearchRequestBuilder srb = elasticSearchClient.prepareSearch(indexName)
        .setQuery(fq)
        .setTypes(docType)
        .storedFields("_id")
        .setFrom(start)
        .setSize(size);

    return srb.get();
}
 
Example 8
Source File: ElasticSearchDAOV5.java    From conductor with Apache License 2.0 6 votes vote down vote up
@Override
public List<EventExecution> getEventExecutions(String event) {
    try {
        Expression expression = Expression.fromString("event='" + event + "'");
        QueryBuilder queryBuilder = expression.getFilterBuilder();

        BoolQueryBuilder filterQuery = QueryBuilders.boolQuery().must(queryBuilder);
        QueryStringQueryBuilder stringQuery = QueryBuilders.queryStringQuery("*");
        BoolQueryBuilder fq = QueryBuilders.boolQuery().must(stringQuery).must(filterQuery);

        final SearchRequestBuilder srb = elasticSearchClient.prepareSearch(logIndexPrefix + "*")
                .setQuery(fq).setTypes(EVENT_DOC_TYPE)
                .addSort(SortBuilders.fieldSort("created")
                        .order(SortOrder.ASC));

        return mapEventExecutionsResponse(srb.execute().actionGet());
    } catch (Exception e) {
        String errorMsg = String.format("Failed to get executions for event: %s", event);
        logger.error(errorMsg, e);
        throw new ApplicationException(Code.BACKEND_ERROR, errorMsg, e);
    }
}
 
Example 9
Source File: ElasticSearchDAOV5.java    From conductor with Apache License 2.0 6 votes vote down vote up
@Override
public List<Message> getMessages(String queue) {
    try {
        Expression expression = Expression.fromString("queue='" + queue + "'");
        QueryBuilder queryBuilder = expression.getFilterBuilder();

        BoolQueryBuilder filterQuery = QueryBuilders.boolQuery().must(queryBuilder);
        QueryStringQueryBuilder stringQuery = QueryBuilders.queryStringQuery("*");
        BoolQueryBuilder fq = QueryBuilders.boolQuery().must(stringQuery).must(filterQuery);

        final SearchRequestBuilder srb = elasticSearchClient.prepareSearch(logIndexPrefix + "*")
                .setQuery(fq)
                .setTypes(MSG_DOC_TYPE)
                .addSort(SortBuilders.fieldSort("created").order(SortOrder.ASC));

        return mapGetMessagesResponse(srb.execute().actionGet());
    } catch (Exception e) {
        String errorMsg = String.format("Failed to get messages for queue: %s", queue);
        logger.error(errorMsg, e);
        throw new ApplicationException(Code.BACKEND_ERROR, errorMsg, e);
    }
}
 
Example 10
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 11
Source File: ElasticSearchRestDAOV5.java    From conductor with Apache License 2.0 5 votes vote down vote up
@Override
public List<Message> getMessages(String queue) {
    try {
        Expression expression = Expression.fromString("queue='" + queue + "'");
        QueryBuilder queryBuilder = expression.getFilterBuilder();

        BoolQueryBuilder filterQuery = QueryBuilders.boolQuery().must(queryBuilder);
        QueryStringQueryBuilder stringQuery = QueryBuilders.queryStringQuery("*");
        BoolQueryBuilder query = QueryBuilders.boolQuery().must(stringQuery).must(filterQuery);

        // Create the searchObjectIdsViaExpression source
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(query);
        searchSourceBuilder.sort(new FieldSortBuilder("created").order(SortOrder.ASC));

        // Generate the actual request to send to ES.
        SearchRequest searchRequest = new SearchRequest(logIndexPrefix + "*");
        searchRequest.types(MSG_DOC_TYPE);
        searchRequest.source(searchSourceBuilder);

        SearchResponse response = elasticSearchClient.search(searchRequest);
        return mapGetMessagesResponse(response);
    } catch (Exception e) {
        logger.error("Failed to get messages for queue: {}", queue, e);
        throw new ApplicationException(ApplicationException.Code.BACKEND_ERROR, e.getMessage(), e);
    }
}
 
Example 12
Source File: ElasticSearchRestDAOV5.java    From conductor with Apache License 2.0 5 votes vote down vote up
@Override
public List<EventExecution> getEventExecutions(String event) {
    try {
        Expression expression = Expression.fromString("event='" + event + "'");
        QueryBuilder queryBuilder = expression.getFilterBuilder();

        BoolQueryBuilder filterQuery = QueryBuilders.boolQuery().must(queryBuilder);
        QueryStringQueryBuilder stringQuery = QueryBuilders.queryStringQuery("*");
        BoolQueryBuilder query = QueryBuilders.boolQuery().must(stringQuery).must(filterQuery);

        // Create the searchObjectIdsViaExpression source
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(query);
        searchSourceBuilder.sort(new FieldSortBuilder("created").order(SortOrder.ASC));

        // Generate the actual request to send to ES.
        SearchRequest searchRequest = new SearchRequest(logIndexPrefix + "*");
        searchRequest.types(EVENT_DOC_TYPE);
        searchRequest.source(searchSourceBuilder);

        SearchResponse response = elasticSearchClient.search(searchRequest);

        return mapEventExecutionsResponse(response);
    } catch (Exception e) {
        logger.error("Failed to get executions for event: {}", event, e);
        throw new ApplicationException(ApplicationException.Code.BACKEND_ERROR, e.getMessage(), e);
    }
}
 
Example 13
Source File: ElasticSearchDAOV5.java    From conductor with Apache License 2.0 5 votes vote down vote up
private SearchResult<String> search(String indexName, String structuredQuery, int start, int size,
    List<String> sortOptions, String freeTextQuery, String docType) {
    try {
        QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
        if (StringUtils.isNotEmpty(structuredQuery)) {
            Expression expression = Expression.fromString(structuredQuery);
            queryBuilder = expression.getFilterBuilder();
        }

        BoolQueryBuilder filterQuery = QueryBuilders.boolQuery().must(queryBuilder);
        QueryStringQueryBuilder stringQuery = QueryBuilders.queryStringQuery(freeTextQuery);
        BoolQueryBuilder fq = QueryBuilders.boolQuery().must(stringQuery).must(filterQuery);
        final SearchRequestBuilder srb = elasticSearchClient.prepareSearch(indexName)
                .setQuery(fq)
                .setTypes(docType)
                .storedFields("_id")
                .setFrom(start)
                .setSize(size);

        if (sortOptions != null) {
            sortOptions.forEach(sortOption -> addSortOptionToSearchRequest(srb, sortOption));
        }

        SearchResponse response = srb.get();

        LinkedList<String> result = StreamSupport.stream(response.getHits().spliterator(), false)
                .map(SearchHit::getId)
                .collect(Collectors.toCollection(LinkedList::new));
        long count = response.getHits().getTotalHits();

        return new SearchResult<>(count, result);
    } catch (ParserException e) {
        String errorMsg = String.format("Error performing search on index:%s with docType:%s", indexName, docType);
        logger.error(errorMsg);
        throw new ApplicationException(Code.BACKEND_ERROR, errorMsg, e);
    }
}
 
Example 14
Source File: EsAbstractConditionQuery.java    From fess with Apache License 2.0 5 votes vote down vote up
protected void doQueryString(String queryString, ConditionOptionCall<QueryStringQueryBuilder> opLambda) {
    QueryStringQueryBuilder queryStringQuery = QueryBuilders.queryStringQuery(queryString);
    regQ(queryStringQuery);
    if (opLambda != null) {
        opLambda.callback(queryStringQuery);
    }
}
 
Example 15
Source File: DecompoundQueryTests.java    From elasticsearch-plugin-bundle with GNU Affero General Public License v3.0 5 votes vote down vote up
public void testCommonPhraseQuery() throws Exception {
    List<IndexRequestBuilder> reqs = new ArrayList<>();
    reqs.add(client().prepareIndex("test", "_doc", "1").setSource("text", "deutsche Spielbankgesellschaft"));
    indexRandom(true, false, reqs);

    QueryStringQueryBuilder queryStringQueryBuilder = QueryBuilders.queryStringQuery("text:\"deutsche bank\"");
    SearchResponse resp = client().prepareSearch("test").setQuery(queryStringQueryBuilder).get();
    ElasticsearchAssertions.assertHitCount(resp, 1L);
    assertHits(resp.getHits(), "1");
}
 
Example 16
Source File: EsAbstractConditionQuery.java    From fess with Apache License 2.0 5 votes vote down vote up
protected void doQueryString(String queryString, ConditionOptionCall<QueryStringQueryBuilder> opLambda) {
    QueryStringQueryBuilder queryStringQuery = QueryBuilders.queryStringQuery(queryString);
    regQ(queryStringQuery);
    if (opLambda != null) {
        opLambda.callback(queryStringQuery);
    }
}
 
Example 17
Source File: QueryClauseFuzzyMatchNgramGenerator.java    From molgenis with GNU Lesser General Public License v3.0 4 votes vote down vote up
QueryBuilder mapQueryRule(QueryRule queryRule, EntityType entityType) {
  String queryField = queryRule.getField();
  Object queryValue = queryRule.getValue();

  QueryBuilder queryBuilder;
  if (queryValue == null) throw new MolgenisQueryException(QUERY_VALUE_CANNOT_BE_NULL_MSG);

  if (queryField == null) {
    queryBuilder = QueryBuilders.matchQuery("_all", queryValue);
  } else {
    Attribute attr = entityType.getAttributeByName(queryField);
    // construct query part
    AttributeType dataType = attr.getDataType();
    switch (dataType) {
      case DATE:
      case DATE_TIME:
      case DECIMAL:
      case EMAIL:
      case ENUM:
      case HTML:
      case HYPERLINK:
      case INT:
      case LONG:
      case SCRIPT:
      case STRING:
      case TEXT:
        queryField = getQueryFieldName(attr) + "." + FIELD_NGRAM;
        queryBuilder = QueryBuilders.queryStringQuery(queryField + ":(" + queryValue + ")");
        break;
      case MREF:
      case XREF:
        queryField =
            getQueryFieldName(attr)
                + "."
                + getQueryFieldName(attr.getRefEntity().getLabelAttribute())
                + "."
                + FIELD_NGRAM;
        queryBuilder =
            QueryBuilders.nestedQuery(
                getQueryFieldName(attr),
                QueryBuilders.queryStringQuery(queryField + ":(" + queryValue + ")"),
                ScoreMode.Max);
        break;
      default:
        throw new UnexpectedEnumException(dataType);
    }
  }
  return queryBuilder;
}
 
Example 18
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 19
Source File: WhereParser.java    From sql4es with Apache License 2.0 4 votes vote down vote up
/**
 * Parses predicats of types =, >, >=, <, <= and <>
 * @param compareExp
 * @param state
 * @return
 */
private QueryWrapper processComparison(ComparisonExpression compareExp, QueryState state) {
	String field = getVariableName(compareExp.getLeft());
	FieldAndType fat = getFieldAndType(field, state);
	field = fat.getFieldName();

	if(compareExp.getRight() instanceof Identifier || compareExp.getRight() instanceof DereferenceExpression){
		state.addException("Matching two columns is not supported : "+compareExp);
		return null;
	}
	// get value of the expression
	Object value = getLiteralValue(compareExp.getRight(), state);
	if(state.hasException()) return null;
	
	QueryBuilder comparison = null;
	String[] types = new String[state.getSources().size()];
	for(int i=0; i<types.length; i++) types[i] = state.getSources().get(i).getSource();
	if(compareExp.getType() == ComparisonExpressionType.EQUAL){
		if(field.equals(Heading.ID)) comparison = QueryBuilders.idsQuery(types).addIds((String)value);
		else if(field.equals(Heading.SEARCH)) comparison = QueryBuilders.queryStringQuery((String)value);
		else if(value instanceof String) comparison = queryForString(field, (String)value);
		else comparison = QueryBuilders.termQuery(field, value);
	}else if(compareExp.getType() == ComparisonExpressionType.GREATER_THAN_OR_EQUAL){
		comparison = QueryBuilders.rangeQuery(field).from(value);
	}else if(compareExp.getType() == ComparisonExpressionType.LESS_THAN_OR_EQUAL){
		comparison = QueryBuilders.rangeQuery(field).to(value);
	}else if(compareExp.getType() == ComparisonExpressionType.GREATER_THAN){
		comparison = QueryBuilders.rangeQuery(field).gt(value);
	}else if(compareExp.getType() == ComparisonExpressionType.LESS_THAN){
		comparison = QueryBuilders.rangeQuery(field).lt(value);
	}else if(compareExp.getType() == ComparisonExpressionType.NOT_EQUAL){
		if(field.equals(Heading.ID)){
			state.addException("Matching document _id using '<>' is not supported");
			return null;
		}
		comparison = QueryBuilders.boolQuery().mustNot(QueryBuilders.termQuery(field, value));
	};
	if(fat.getFieldType() == Types.REF) 
		return new QueryWrapper( comparison, field.split("\\.")[0]);
	return new QueryWrapper(comparison);
}
 
Example 20
Source File: QueryStringQueryParser.java    From elasticsearch-sql with MIT License 4 votes vote down vote up
@Override
public AtomicQuery parse(ElasticsearchParser.QueryStringClauseContext expression) {
    String text = StringManager.removeStringSymbol(expression.STRING().getText());
    return new AtomicQuery(QueryBuilders.queryStringQuery(text));
}