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());
}
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"));
}
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();
}
}
});
}
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]"));
}
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;
}
}
}
Aggregations