Search in sources :

Example 11 with QueryBuilder

use of org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryBuilder in project elasticsearch by elastic.

the class RestExplainAction method prepareRequest.

@Override
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
    final ExplainRequest explainRequest = new ExplainRequest(request.param("index"), request.param("type"), request.param("id"));
    explainRequest.parent(request.param("parent"));
    explainRequest.routing(request.param("routing"));
    explainRequest.preference(request.param("preference"));
    String queryString = request.param("q");
    request.withContentOrSourceParamParserOrNull(parser -> {
        if (parser != null) {
            explainRequest.query(RestActions.getQueryContent(parser));
        } else if (queryString != null) {
            QueryBuilder query = RestActions.urlParamsToQueryBuilder(request);
            explainRequest.query(query);
        }
    });
    if (request.param("fields") != null) {
        throw new IllegalArgumentException("The parameter [fields] is no longer supported, " + "please use [stored_fields] to retrieve stored fields");
    }
    String sField = request.param("stored_fields");
    if (sField != null) {
        String[] sFields = Strings.splitStringByCommaToArray(sField);
        if (sFields != null) {
            explainRequest.storedFields(sFields);
        }
    }
    explainRequest.fetchSourceContext(FetchSourceContext.parseFromRestRequest(request));
    return channel -> client.explain(explainRequest, new RestBuilderListener<ExplainResponse>(channel) {

        @Override
        public RestResponse buildResponse(ExplainResponse response, XContentBuilder builder) throws Exception {
            builder.startObject();
            builder.field(Fields._INDEX, response.getIndex()).field(Fields._TYPE, response.getType()).field(Fields._ID, response.getId()).field(Fields.MATCHED, response.isMatch());
            if (response.hasExplanation()) {
                builder.startObject(Fields.EXPLANATION);
                buildExplanation(builder, response.getExplanation());
                builder.endObject();
            }
            GetResult getResult = response.getGetResult();
            if (getResult != null) {
                builder.startObject(Fields.GET);
                response.getGetResult().toXContentEmbedded(builder, request);
                builder.endObject();
            }
            builder.endObject();
            return new BytesRestResponse(response.isExists() ? OK : NOT_FOUND, builder);
        }

        private void buildExplanation(XContentBuilder builder, Explanation explanation) throws IOException {
            builder.field(Fields.VALUE, explanation.getValue());
            builder.field(Fields.DESCRIPTION, explanation.getDescription());
            Explanation[] innerExps = explanation.getDetails();
            if (innerExps != null) {
                builder.startArray(Fields.DETAILS);
                for (Explanation exp : innerExps) {
                    builder.startObject();
                    buildExplanation(builder, exp);
                    builder.endObject();
                }
                builder.endArray();
            }
        }
    });
}
Also used : BaseRestHandler(org.elasticsearch.rest.BaseRestHandler) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) Explanation(org.apache.lucene.search.Explanation) GET(org.elasticsearch.rest.RestRequest.Method.GET) ExplainRequest(org.elasticsearch.action.explain.ExplainRequest) ExplainResponse(org.elasticsearch.action.explain.ExplainResponse) RestResponse(org.elasticsearch.rest.RestResponse) GetResult(org.elasticsearch.index.get.GetResult) RestBuilderListener(org.elasticsearch.rest.action.RestBuilderListener) IOException(java.io.IOException) NOT_FOUND(org.elasticsearch.rest.RestStatus.NOT_FOUND) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) RestController(org.elasticsearch.rest.RestController) Strings(org.elasticsearch.common.Strings) RestActions(org.elasticsearch.rest.action.RestActions) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) POST(org.elasticsearch.rest.RestRequest.Method.POST) Settings(org.elasticsearch.common.settings.Settings) RestRequest(org.elasticsearch.rest.RestRequest) OK(org.elasticsearch.rest.RestStatus.OK) NodeClient(org.elasticsearch.client.node.NodeClient) FetchSourceContext(org.elasticsearch.search.fetch.subphase.FetchSourceContext) GetResult(org.elasticsearch.index.get.GetResult) RestResponse(org.elasticsearch.rest.RestResponse) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) Explanation(org.apache.lucene.search.Explanation) ExplainResponse(org.elasticsearch.action.explain.ExplainResponse) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) IOException(java.io.IOException) ExplainRequest(org.elasticsearch.action.explain.ExplainRequest) IOException(java.io.IOException) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder)

Example 12 with QueryBuilder

use of org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryBuilder in project elasticsearch by elastic.

the class TemplateQueryBuilderTests method testMustRewrite.

@Override
public void testMustRewrite() throws IOException {
    String query = "{ \"match_all\" : {}}";
    QueryBuilder builder = new TemplateQueryBuilder(new Script(ScriptType.INLINE, "mockscript", query, Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType()), Collections.emptyMap()));
    try {
        builder.toQuery(createShardContext());
        fail();
    } catch (UnsupportedOperationException ex) {
        assertEquals("this query must be rewritten first", ex.getMessage());
    }
    assertEquals(new MatchAllQueryBuilder(), builder.rewrite(createShardContext()));
}
Also used : Script(org.elasticsearch.script.Script) Matchers.containsString(org.hamcrest.Matchers.containsString) MatchQueryBuilder(org.elasticsearch.index.query.MatchQueryBuilder) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) TermQueryBuilder(org.elasticsearch.index.query.TermQueryBuilder) MatchAllQueryBuilder(org.elasticsearch.index.query.MatchAllQueryBuilder) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) MatchAllQueryBuilder(org.elasticsearch.index.query.MatchAllQueryBuilder)

Example 13 with QueryBuilder

use of org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryBuilder in project elasticsearch by elastic.

the class PercolatorFieldMapperTests method testMultiplePercolatorFields.

// multiple percolator fields are allowed in the mapping, but only one field can be used at index time.
public void testMultiplePercolatorFields() throws Exception {
    String typeName = "another_type";
    String percolatorMapper = XContentFactory.jsonBuilder().startObject().startObject(typeName).startObject("_field_names").field("enabled", false).endObject().startObject("properties").startObject("query_field1").field("type", "percolator").endObject().startObject("query_field2").field("type", "percolator").endObject().endObject().endObject().endObject().string();
    mapperService.merge(typeName, new CompressedXContent(percolatorMapper), MapperService.MergeReason.MAPPING_UPDATE, true);
    QueryBuilder queryBuilder = matchQuery("field", "value");
    ParsedDocument doc = mapperService.documentMapper(typeName).parse("test", typeName, "1", jsonBuilder().startObject().field("query_field1", queryBuilder).field("query_field2", queryBuilder).endObject().bytes());
    // also includes all other meta fields
    assertThat(doc.rootDoc().getFields().size(), equalTo(14));
    BytesRef queryBuilderAsBytes = doc.rootDoc().getField("query_field1.query_builder_field").binaryValue();
    assertQueryBuilder(queryBuilderAsBytes, queryBuilder);
    queryBuilderAsBytes = doc.rootDoc().getField("query_field2.query_builder_field").binaryValue();
    assertQueryBuilder(queryBuilderAsBytes, queryBuilder);
}
Also used : ParsedDocument(org.elasticsearch.index.mapper.ParsedDocument) CompressedXContent(org.elasticsearch.common.compress.CompressedXContent) Matchers.containsString(org.hamcrest.Matchers.containsString) HasParentQueryBuilder(org.elasticsearch.index.query.HasParentQueryBuilder) RangeQueryBuilder(org.elasticsearch.index.query.RangeQueryBuilder) MatchAllQueryBuilder(org.elasticsearch.index.query.MatchAllQueryBuilder) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) ConstantScoreQueryBuilder(org.elasticsearch.index.query.ConstantScoreQueryBuilder) FunctionScoreQueryBuilder(org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) BoostingQueryBuilder(org.elasticsearch.index.query.BoostingQueryBuilder) HasChildQueryBuilder(org.elasticsearch.index.query.HasChildQueryBuilder) BytesRef(org.apache.lucene.util.BytesRef)

Example 14 with QueryBuilder

use of org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryBuilder in project elasticsearch by elastic.

the class PercolatorFieldMapperTests method testPercolatorFieldMapper.

public void testPercolatorFieldMapper() throws Exception {
    addQueryMapping();
    QueryBuilder queryBuilder = termQuery("field", "value");
    ParsedDocument doc = mapperService.documentMapper(typeName).parse("test", typeName, "1", XContentFactory.jsonBuilder().startObject().field(fieldName, queryBuilder).endObject().bytes());
    assertThat(doc.rootDoc().getFields(fieldType.queryTermsField.name()).length, equalTo(1));
    assertThat(doc.rootDoc().getFields(fieldType.queryTermsField.name())[0].binaryValue().utf8ToString(), equalTo("field\0value"));
    assertThat(doc.rootDoc().getFields(fieldType.queryBuilderField.name()).length, equalTo(1));
    assertThat(doc.rootDoc().getFields(fieldType.extractionResultField.name()).length, equalTo(1));
    assertThat(doc.rootDoc().getFields(fieldType.extractionResultField.name())[0].stringValue(), equalTo(EXTRACTION_COMPLETE));
    BytesRef qbSource = doc.rootDoc().getFields(fieldType.queryBuilderField.name())[0].binaryValue();
    assertQueryBuilder(qbSource, queryBuilder);
    // add an query for which we don't extract terms from
    queryBuilder = rangeQuery("field").from("a").to("z");
    doc = mapperService.documentMapper(typeName).parse("test", typeName, "1", XContentFactory.jsonBuilder().startObject().field(fieldName, queryBuilder).endObject().bytes());
    assertThat(doc.rootDoc().getFields(fieldType.extractionResultField.name()).length, equalTo(1));
    assertThat(doc.rootDoc().getFields(fieldType.extractionResultField.name())[0].stringValue(), equalTo(EXTRACTION_FAILED));
    assertThat(doc.rootDoc().getFields(fieldType.queryTermsField.name()).length, equalTo(0));
    assertThat(doc.rootDoc().getFields(fieldType.queryBuilderField.name()).length, equalTo(1));
    qbSource = doc.rootDoc().getFields(fieldType.queryBuilderField.name())[0].binaryValue();
    assertQueryBuilder(qbSource, queryBuilder);
}
Also used : ParsedDocument(org.elasticsearch.index.mapper.ParsedDocument) HasParentQueryBuilder(org.elasticsearch.index.query.HasParentQueryBuilder) RangeQueryBuilder(org.elasticsearch.index.query.RangeQueryBuilder) MatchAllQueryBuilder(org.elasticsearch.index.query.MatchAllQueryBuilder) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) ConstantScoreQueryBuilder(org.elasticsearch.index.query.ConstantScoreQueryBuilder) FunctionScoreQueryBuilder(org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) BoostingQueryBuilder(org.elasticsearch.index.query.BoostingQueryBuilder) HasChildQueryBuilder(org.elasticsearch.index.query.HasChildQueryBuilder) BytesRef(org.apache.lucene.util.BytesRef)

Example 15 with QueryBuilder

use of org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryBuilder in project elasticsearch by elastic.

the class PercolatorFieldMapperTests method testStoringQueries.

public void testStoringQueries() throws Exception {
    addQueryMapping();
    QueryBuilder[] queries = new QueryBuilder[] { termQuery("field", "value"), matchAllQuery(), matchQuery("field", "value"), matchPhraseQuery("field", "value"), prefixQuery("field", "v"), wildcardQuery("field", "v*"), rangeQuery("number_field").gte(0).lte(9), rangeQuery("date_field").from("2015-01-01T00:00").to("2015-01-01T00:00") };
    for (QueryBuilder query : queries) {
        ParsedDocument doc = mapperService.documentMapper(typeName).parse("test", typeName, "1", XContentFactory.jsonBuilder().startObject().field(fieldName, query).endObject().bytes());
        BytesRef qbSource = doc.rootDoc().getFields(fieldType.queryBuilderField.name())[0].binaryValue();
        assertQueryBuilder(qbSource, query);
    }
}
Also used : ParsedDocument(org.elasticsearch.index.mapper.ParsedDocument) HasParentQueryBuilder(org.elasticsearch.index.query.HasParentQueryBuilder) RangeQueryBuilder(org.elasticsearch.index.query.RangeQueryBuilder) MatchAllQueryBuilder(org.elasticsearch.index.query.MatchAllQueryBuilder) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) ConstantScoreQueryBuilder(org.elasticsearch.index.query.ConstantScoreQueryBuilder) FunctionScoreQueryBuilder(org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) BoostingQueryBuilder(org.elasticsearch.index.query.BoostingQueryBuilder) HasChildQueryBuilder(org.elasticsearch.index.query.HasChildQueryBuilder) BytesRef(org.apache.lucene.util.BytesRef)

Aggregations

QueryBuilder (org.elasticsearch.index.query.QueryBuilder)371 BoolQueryBuilder (org.elasticsearch.index.query.BoolQueryBuilder)245 Test (org.testng.annotations.Test)156 DynamicEntity (org.molgenis.data.support.DynamicEntity)137 SearchResponse (org.elasticsearch.action.search.SearchResponse)58 QueryImpl (org.molgenis.data.support.QueryImpl)36 Map (java.util.Map)32 Test (org.junit.Test)31 ArrayList (java.util.ArrayList)30 SearchSourceBuilder (org.elasticsearch.search.builder.SearchSourceBuilder)29 HashMap (java.util.HashMap)27 MatchAllQueryBuilder (org.elasticsearch.index.query.MatchAllQueryBuilder)27 RangeQueryBuilder (org.elasticsearch.index.query.RangeQueryBuilder)27 IOException (java.io.IOException)23 SearchHit (org.elasticsearch.search.SearchHit)22 AbstractQueryBuilder (org.elasticsearch.index.query.AbstractQueryBuilder)19 TermQueryBuilder (org.elasticsearch.index.query.TermQueryBuilder)19 SearchRequestBuilder (org.elasticsearch.action.search.SearchRequestBuilder)17 List (java.util.List)16 IndexRequestBuilder (org.elasticsearch.action.index.IndexRequestBuilder)15