Search in sources :

Example 1 with ExplainResponse

use of org.elasticsearch.action.explain.ExplainResponse in project elasticsearch by elastic.

the class ExplainActionIT method testExplainWithFilteredAlias.

public void testExplainWithFilteredAlias() throws Exception {
    assertAcked(prepareCreate("test").addMapping("test", "field2", "type=text").addAlias(new Alias("alias1").filter(QueryBuilders.termQuery("field2", "value2"))));
    ensureGreen("test");
    client().prepareIndex("test", "test", "1").setSource("field1", "value1", "field2", "value1").get();
    refresh();
    ExplainResponse response = client().prepareExplain("alias1", "test", "1").setQuery(QueryBuilders.matchAllQuery()).get();
    assertNotNull(response);
    assertTrue(response.isExists());
    assertFalse(response.isMatch());
}
Also used : Alias(org.elasticsearch.action.admin.indices.alias.Alias) ExplainResponse(org.elasticsearch.action.explain.ExplainResponse)

Example 2 with ExplainResponse

use of org.elasticsearch.action.explain.ExplainResponse in project elasticsearch by elastic.

the class ExplainActionIT method testExplainWithFilteredAliasFetchSource.

public void testExplainWithFilteredAliasFetchSource() throws Exception {
    assertAcked(client().admin().indices().prepareCreate("test").addMapping("test", "field2", "type=text").addAlias(new Alias("alias1").filter(QueryBuilders.termQuery("field2", "value2"))));
    ensureGreen("test");
    client().prepareIndex("test", "test", "1").setSource("field1", "value1", "field2", "value1").get();
    refresh();
    ExplainResponse response = client().prepareExplain("alias1", "test", "1").setQuery(QueryBuilders.matchAllQuery()).setFetchSource(true).get();
    assertNotNull(response);
    assertTrue(response.isExists());
    assertFalse(response.isMatch());
    assertThat(response.getIndex(), equalTo("test"));
    assertThat(response.getType(), equalTo("test"));
    assertThat(response.getId(), equalTo("1"));
    assertThat(response.getGetResult(), notNullValue());
    assertThat(response.getGetResult().getIndex(), equalTo("test"));
    assertThat(response.getGetResult().getType(), equalTo("test"));
    assertThat(response.getGetResult().getId(), equalTo("1"));
    assertThat(response.getGetResult().getSource(), notNullValue());
    assertThat((String) response.getGetResult().getSource().get("field1"), equalTo("value1"));
}
Also used : Alias(org.elasticsearch.action.admin.indices.alias.Alias) ExplainResponse(org.elasticsearch.action.explain.ExplainResponse)

Example 3 with ExplainResponse

use of org.elasticsearch.action.explain.ExplainResponse 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 4 with ExplainResponse

use of org.elasticsearch.action.explain.ExplainResponse in project elasticsearch by elastic.

the class SimpleRoutingIT method testRequiredRoutingMappingVariousAPIs.

public void testRequiredRoutingMappingVariousAPIs() throws Exception {
    client().admin().indices().prepareCreate("test").addAlias(new Alias("alias")).addMapping("type1", XContentFactory.jsonBuilder().startObject().startObject("type1").startObject("_routing").field("required", true).endObject().endObject().endObject()).execute().actionGet();
    ensureGreen();
    logger.info("--> indexing with id [1], and routing [0]");
    client().prepareIndex(indexOrAlias(), "type1", "1").setRouting("0").setSource("field", "value1").get();
    logger.info("--> indexing with id [2], and routing [0]");
    client().prepareIndex(indexOrAlias(), "type1", "2").setRouting("0").setSource("field", "value2").setRefreshPolicy(RefreshPolicy.IMMEDIATE).get();
    logger.info("--> verifying get with id [1] with routing [0], should succeed");
    assertThat(client().prepareGet(indexOrAlias(), "type1", "1").setRouting("0").execute().actionGet().isExists(), equalTo(true));
    logger.info("--> verifying get with id [1], with no routing, should fail");
    try {
        client().prepareGet(indexOrAlias(), "type1", "1").get();
        fail();
    } catch (RoutingMissingException e) {
        assertThat(e.getMessage(), equalTo("routing is required for [test]/[type1]/[1]"));
    }
    logger.info("--> verifying explain with id [2], with routing [0], should succeed");
    ExplainResponse explainResponse = client().prepareExplain(indexOrAlias(), "type1", "2").setQuery(QueryBuilders.matchAllQuery()).setRouting("0").get();
    assertThat(explainResponse.isExists(), equalTo(true));
    assertThat(explainResponse.isMatch(), equalTo(true));
    logger.info("--> verifying explain with id [2], with no routing, should fail");
    try {
        client().prepareExplain(indexOrAlias(), "type1", "2").setQuery(QueryBuilders.matchAllQuery()).get();
        fail();
    } catch (RoutingMissingException e) {
        assertThat(e.getMessage(), equalTo("routing is required for [test]/[type1]/[2]"));
    }
    logger.info("--> verifying term vector with id [1], with routing [0], should succeed");
    TermVectorsResponse termVectorsResponse = client().prepareTermVectors(indexOrAlias(), "type1", "1").setRouting("0").get();
    assertThat(termVectorsResponse.isExists(), equalTo(true));
    assertThat(termVectorsResponse.getId(), equalTo("1"));
    try {
        client().prepareTermVectors(indexOrAlias(), "type1", "1").get();
        fail();
    } catch (RoutingMissingException e) {
        assertThat(e.getMessage(), equalTo("routing is required for [test]/[type1]/[1]"));
    }
    UpdateResponse updateResponse = client().prepareUpdate(indexOrAlias(), "type1", "1").setRouting("0").setDoc(Requests.INDEX_CONTENT_TYPE, "field1", "value1").get();
    assertThat(updateResponse.getId(), equalTo("1"));
    assertThat(updateResponse.getVersion(), equalTo(2L));
    try {
        client().prepareUpdate(indexOrAlias(), "type1", "1").setDoc(Requests.INDEX_CONTENT_TYPE, "field1", "value1").get();
        fail();
    } catch (RoutingMissingException e) {
        assertThat(e.getMessage(), equalTo("routing is required for [test]/[type1]/[1]"));
    }
    logger.info("--> verifying mget with ids [1,2], with routing [0], should succeed");
    MultiGetResponse multiGetResponse = client().prepareMultiGet().add(new MultiGetRequest.Item(indexOrAlias(), "type1", "1").routing("0")).add(new MultiGetRequest.Item(indexOrAlias(), "type1", "2").routing("0")).get();
    assertThat(multiGetResponse.getResponses().length, equalTo(2));
    assertThat(multiGetResponse.getResponses()[0].isFailed(), equalTo(false));
    assertThat(multiGetResponse.getResponses()[0].getResponse().getId(), equalTo("1"));
    assertThat(multiGetResponse.getResponses()[1].isFailed(), equalTo(false));
    assertThat(multiGetResponse.getResponses()[1].getResponse().getId(), equalTo("2"));
    logger.info("--> verifying mget with ids [1,2], with no routing, should fail");
    multiGetResponse = client().prepareMultiGet().add(new MultiGetRequest.Item(indexOrAlias(), "type1", "1")).add(new MultiGetRequest.Item(indexOrAlias(), "type1", "2")).get();
    assertThat(multiGetResponse.getResponses().length, equalTo(2));
    assertThat(multiGetResponse.getResponses()[0].isFailed(), equalTo(true));
    assertThat(multiGetResponse.getResponses()[0].getFailure().getId(), equalTo("1"));
    assertThat(multiGetResponse.getResponses()[0].getFailure().getMessage(), equalTo("routing is required for [test]/[type1]/[1]"));
    assertThat(multiGetResponse.getResponses()[1].isFailed(), equalTo(true));
    assertThat(multiGetResponse.getResponses()[1].getFailure().getId(), equalTo("2"));
    assertThat(multiGetResponse.getResponses()[1].getFailure().getMessage(), equalTo("routing is required for [test]/[type1]/[2]"));
    MultiTermVectorsResponse multiTermVectorsResponse = client().prepareMultiTermVectors().add(new TermVectorsRequest(indexOrAlias(), "type1", "1").routing("0")).add(new TermVectorsRequest(indexOrAlias(), "type1", "2").routing("0")).get();
    assertThat(multiTermVectorsResponse.getResponses().length, equalTo(2));
    assertThat(multiTermVectorsResponse.getResponses()[0].getId(), equalTo("1"));
    assertThat(multiTermVectorsResponse.getResponses()[0].isFailed(), equalTo(false));
    assertThat(multiTermVectorsResponse.getResponses()[0].getResponse().getId(), equalTo("1"));
    assertThat(multiTermVectorsResponse.getResponses()[0].getResponse().isExists(), equalTo(true));
    assertThat(multiTermVectorsResponse.getResponses()[1].getId(), equalTo("2"));
    assertThat(multiTermVectorsResponse.getResponses()[1].isFailed(), equalTo(false));
    assertThat(multiTermVectorsResponse.getResponses()[1].getResponse().getId(), equalTo("2"));
    assertThat(multiTermVectorsResponse.getResponses()[1].getResponse().isExists(), equalTo(true));
    multiTermVectorsResponse = client().prepareMultiTermVectors().add(new TermVectorsRequest(indexOrAlias(), "type1", "1")).add(new TermVectorsRequest(indexOrAlias(), "type1", "2")).get();
    assertThat(multiTermVectorsResponse.getResponses().length, equalTo(2));
    assertThat(multiTermVectorsResponse.getResponses()[0].getId(), equalTo("1"));
    assertThat(multiTermVectorsResponse.getResponses()[0].isFailed(), equalTo(true));
    assertThat(multiTermVectorsResponse.getResponses()[0].getFailure().getCause().getMessage(), equalTo("routing is required for [test]/[type1]/[1]"));
    assertThat(multiTermVectorsResponse.getResponses()[0].getResponse(), nullValue());
    assertThat(multiTermVectorsResponse.getResponses()[1].getId(), equalTo("2"));
    assertThat(multiTermVectorsResponse.getResponses()[1].isFailed(), equalTo(true));
    assertThat(multiTermVectorsResponse.getResponses()[1].getResponse(), nullValue());
    assertThat(multiTermVectorsResponse.getResponses()[1].getFailure().getCause().getMessage(), equalTo("routing is required for [test]/[type1]/[2]"));
}
Also used : TermVectorsRequest(org.elasticsearch.action.termvectors.TermVectorsRequest) MultiTermVectorsResponse(org.elasticsearch.action.termvectors.MultiTermVectorsResponse) TermVectorsResponse(org.elasticsearch.action.termvectors.TermVectorsResponse) UpdateResponse(org.elasticsearch.action.update.UpdateResponse) MultiGetResponse(org.elasticsearch.action.get.MultiGetResponse) Alias(org.elasticsearch.action.admin.indices.alias.Alias) ExplainResponse(org.elasticsearch.action.explain.ExplainResponse) RoutingMissingException(org.elasticsearch.action.RoutingMissingException) MultiTermVectorsResponse(org.elasticsearch.action.termvectors.MultiTermVectorsResponse) MultiGetRequest(org.elasticsearch.action.get.MultiGetRequest)

Example 5 with ExplainResponse

use of org.elasticsearch.action.explain.ExplainResponse in project elasticsearch by elastic.

the class ExistsIT method testExists.

public void testExists() throws Exception {
    XContentBuilder mapping = XContentBuilder.builder(JsonXContent.jsonXContent).startObject().startObject("type").startObject("properties").startObject("foo").field("type", "text").endObject().startObject("bar").field("type", "object").startObject("properties").startObject("foo").field("type", "text").endObject().startObject("bar").field("type", "object").startObject("properties").startObject("bar").field("type", "text").endObject().endObject().endObject().startObject("baz").field("type", "long").endObject().endObject().endObject().endObject().endObject().endObject();
    assertAcked(client().admin().indices().prepareCreate("idx").addMapping("type", mapping));
    Map<String, Object> barObject = new HashMap<>();
    barObject.put("foo", "bar");
    barObject.put("bar", singletonMap("bar", "foo"));
    @SuppressWarnings("unchecked") final Map<String, Object>[] sources = new Map[] { // simple property
    singletonMap("foo", "bar"), // object fields
    singletonMap("bar", barObject), singletonMap("bar", singletonMap("baz", 42)), // empty doc
    emptyMap() };
    List<IndexRequestBuilder> reqs = new ArrayList<IndexRequestBuilder>();
    for (Map<String, Object> source : sources) {
        reqs.add(client().prepareIndex("idx", "type").setSource(source));
    }
    // We do NOT index dummy documents, otherwise the type for these dummy documents
    // would have _field_names indexed while the current type might not which might
    // confuse the exists/missing parser at query time
    indexRandom(true, false, reqs);
    final Map<String, Integer> expected = new LinkedHashMap<String, Integer>();
    expected.put("foo", 1);
    expected.put("f*", 1);
    expected.put("bar", 2);
    expected.put("bar.*", 2);
    expected.put("bar.foo", 1);
    expected.put("bar.bar", 1);
    expected.put("bar.bar.bar", 1);
    expected.put("foobar", 0);
    final long numDocs = sources.length;
    SearchResponse allDocs = client().prepareSearch("idx").setSize(sources.length).get();
    assertSearchResponse(allDocs);
    assertHitCount(allDocs, numDocs);
    for (Map.Entry<String, Integer> entry : expected.entrySet()) {
        final String fieldName = entry.getKey();
        final int count = entry.getValue();
        // exists
        SearchResponse resp = client().prepareSearch("idx").setQuery(QueryBuilders.existsQuery(fieldName)).execute().actionGet();
        assertSearchResponse(resp);
        try {
            assertEquals(String.format(Locale.ROOT, "exists(%s, %d) mapping: %s response: %s", fieldName, count, mapping.string(), resp), count, resp.getHits().getTotalHits());
        } catch (AssertionError e) {
            for (SearchHit searchHit : allDocs.getHits()) {
                final String index = searchHit.getIndex();
                final String type = searchHit.getType();
                final String id = searchHit.getId();
                final ExplainResponse explanation = client().prepareExplain(index, type, id).setQuery(QueryBuilders.existsQuery(fieldName)).get();
                logger.info("Explanation for [{}] / [{}] / [{}]: [{}]", fieldName, id, searchHit.getSourceAsString(), explanation.getExplanation());
            }
            throw e;
        }
    }
}
Also used : SearchHit(org.elasticsearch.search.SearchHit) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ExplainResponse(org.elasticsearch.action.explain.ExplainResponse) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) SearchResponse(org.elasticsearch.action.search.SearchResponse) ElasticsearchAssertions.assertSearchResponse(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse) IndexRequestBuilder(org.elasticsearch.action.index.IndexRequestBuilder) Collections.emptyMap(java.util.Collections.emptyMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) Collections.singletonMap(java.util.Collections.singletonMap) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder)

Aggregations

ExplainResponse (org.elasticsearch.action.explain.ExplainResponse)10 Alias (org.elasticsearch.action.admin.indices.alias.Alias)6 Map (java.util.Map)2 SearchResponse (org.elasticsearch.action.search.SearchResponse)2 XContentBuilder (org.elasticsearch.common.xcontent.XContentBuilder)2 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 Collections.emptyMap (java.util.Collections.emptyMap)1 Collections.singletonMap (java.util.Collections.singletonMap)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 LinkedHashMap (java.util.LinkedHashMap)1 Explanation (org.apache.lucene.search.Explanation)1 RoutingMissingException (org.elasticsearch.action.RoutingMissingException)1 ExplainRequest (org.elasticsearch.action.explain.ExplainRequest)1 MultiGetRequest (org.elasticsearch.action.get.MultiGetRequest)1 MultiGetResponse (org.elasticsearch.action.get.MultiGetResponse)1 IndexRequestBuilder (org.elasticsearch.action.index.IndexRequestBuilder)1 MultiTermVectorsResponse (org.elasticsearch.action.termvectors.MultiTermVectorsResponse)1 TermVectorsRequest (org.elasticsearch.action.termvectors.TermVectorsRequest)1