Add HLRC support for enrich get policy API. (#45970)

Changed the signature of AbstractResponseTestCase#createServerTestInstance(...)
to include the randomly selected xcontent type. This is needed for the
creating a server response instance with a query which is represented as BytesReference.
Maybe this should go into a different change?

This PR also includes HLRC docs for the get policy api.

Relates to #32789
This commit is contained in:
Martijn van Groningen 2019-09-11 14:26:42 +02:00
parent a4b0f66919
commit 60ad099178
No known key found for this signature in database
GPG Key ID: AB236F4FCF2AF12A
12 changed files with 515 additions and 40 deletions

View File

@ -21,6 +21,8 @@ package org.elasticsearch.client;
import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.ActionListener;
import org.elasticsearch.client.core.AcknowledgedResponse; import org.elasticsearch.client.core.AcknowledgedResponse;
import org.elasticsearch.client.enrich.DeletePolicyRequest; import org.elasticsearch.client.enrich.DeletePolicyRequest;
import org.elasticsearch.client.enrich.GetPolicyRequest;
import org.elasticsearch.client.enrich.GetPolicyResponse;
import org.elasticsearch.client.enrich.PutPolicyRequest; import org.elasticsearch.client.enrich.PutPolicyRequest;
import java.io.IOException; import java.io.IOException;
@ -128,4 +130,48 @@ public final class EnrichClient {
Collections.emptySet() Collections.emptySet()
); );
} }
/**
* Executes the get policy api, which retrieves an enrich policy.
*
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/enrich-policy-apis.html#get-policy-api">
* the docs</a> for more.
*
* @param request the {@link PutPolicyRequest}
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public GetPolicyResponse getPolicy(GetPolicyRequest request, RequestOptions options) throws IOException {
return restHighLevelClient.performRequestAndParseEntity(
request,
EnrichRequestConverters::getPolicy,
options,
GetPolicyResponse::fromXContent,
Collections.emptySet()
);
}
/**
* Asynchronously executes the get policy api, which retrieves an enrich policy.
*
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/enrich-policy-apis.html#get-policy-api">
* the docs</a> for more.
*
* @param request the {@link PutPolicyRequest}
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public void getPolicyAsync(GetPolicyRequest request,
RequestOptions options,
ActionListener<GetPolicyResponse> listener) {
restHighLevelClient.performRequestAsyncAndParseEntity(
request,
EnrichRequestConverters::getPolicy,
options,
GetPolicyResponse::fromXContent,
listener,
Collections.emptySet()
);
}
} }

View File

@ -19,8 +19,10 @@
package org.elasticsearch.client; package org.elasticsearch.client;
import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpPut;
import org.elasticsearch.client.enrich.DeletePolicyRequest; import org.elasticsearch.client.enrich.DeletePolicyRequest;
import org.elasticsearch.client.enrich.GetPolicyRequest;
import org.elasticsearch.client.enrich.PutPolicyRequest; import org.elasticsearch.client.enrich.PutPolicyRequest;
import java.io.IOException; import java.io.IOException;
@ -48,4 +50,12 @@ final class EnrichRequestConverters {
return new Request(HttpDelete.METHOD_NAME, endpoint); return new Request(HttpDelete.METHOD_NAME, endpoint);
} }
static Request getPolicy(GetPolicyRequest getPolicyRequest) throws IOException {
String endpoint = new RequestConverters.EndpointBuilder()
.addPathPartAsIs("_enrich", "policy")
.addCommaSeparatedPathParts(getPolicyRequest.getNames())
.build();
return new Request(HttpGet.METHOD_NAME, endpoint);
}
} }

View File

@ -0,0 +1,46 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.enrich;
import org.elasticsearch.client.Validatable;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public final class GetPolicyRequest implements Validatable {
private final List<String> names;
public GetPolicyRequest() {
this(Collections.emptyList());
}
public GetPolicyRequest(String... names) {
this(Arrays.asList(names));
}
public GetPolicyRequest(List<String> names) {
this.names = names;
}
public List<String> getNames() {
return names;
}
}

View File

@ -0,0 +1,55 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.enrich;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException;
import java.util.List;
public final class GetPolicyResponse {
@SuppressWarnings("unchecked")
private static final ConstructingObjectParser<GetPolicyResponse, Void> PARSER = new ConstructingObjectParser<>(
"get_policy_response",
true,
args -> new GetPolicyResponse((List<NamedPolicy>) args[0])
);
static {
PARSER.declareObjectArray(ConstructingObjectParser.constructorArg(),
(p, c) -> NamedPolicy.fromXContent(p), new ParseField("policies"));
}
private final List<NamedPolicy> policies;
public static GetPolicyResponse fromXContent(XContentParser parser) throws IOException {
return PARSER.apply(parser, null);
}
public GetPolicyResponse(List<NamedPolicy> policies) {
this.policies = policies;
}
public List<NamedPolicy> getPolicies() {
return policies;
}
}

View File

@ -0,0 +1,130 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.enrich;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException;
import java.util.List;
public final class NamedPolicy {
static final ParseField NAME_FIELD = new ParseField("name");
static final ParseField QUERY_FIELD = new ParseField("query");
static final ParseField INDICES_FIELD = new ParseField("indices");
static final ParseField MATCH_FIELD_FIELD = new ParseField("match_field");
static final ParseField ENRICH_FIELDS_FIELD = new ParseField("enrich_fields");
@SuppressWarnings("unchecked")
private static final ConstructingObjectParser<NamedPolicy, String> PARSER = new ConstructingObjectParser<>(
"policy",
true,
(args, policyType) -> new NamedPolicy(
policyType,
(String) args[0],
(BytesReference) args[1],
(List<String>) args[2],
(String) args[3],
(List<String>) args[4]
)
);
static {
declareParserOptions(PARSER);
}
private static void declareParserOptions(ConstructingObjectParser<?, ?> parser) {
parser.declareString(ConstructingObjectParser.constructorArg(), NAME_FIELD);
parser.declareObject(ConstructingObjectParser.optionalConstructorArg(), (p, c) -> {
XContentBuilder builder = XContentBuilder.builder(p.contentType().xContent());
builder.copyCurrentStructure(p);
return BytesArray.bytes(builder);
}, QUERY_FIELD);
parser.declareStringArray(ConstructingObjectParser.constructorArg(), INDICES_FIELD);
parser.declareString(ConstructingObjectParser.constructorArg(), MATCH_FIELD_FIELD);
parser.declareStringArray(ConstructingObjectParser.constructorArg(), ENRICH_FIELDS_FIELD);
}
public static NamedPolicy fromXContent(XContentParser parser) throws IOException {
XContentParser.Token token = parser.currentToken();
if (token != XContentParser.Token.START_OBJECT) {
token = parser.nextToken();
}
if (token != XContentParser.Token.START_OBJECT) {
throw new ParsingException(parser.getTokenLocation(), "unexpected token");
}
token = parser.nextToken();
if (token != XContentParser.Token.FIELD_NAME) {
throw new ParsingException(parser.getTokenLocation(), "unexpected token");
}
String policyType = parser.currentName();
NamedPolicy policy = PARSER.parse(parser, policyType);
token = parser.nextToken();
if (token != XContentParser.Token.END_OBJECT) {
throw new ParsingException(parser.getTokenLocation(), "unexpected token");
}
return policy;
}
private final String type;
private final String name;
private final BytesReference query;
private final List<String> indices;
private final String matchField;
private final List<String> enrichFields;
NamedPolicy(String type, String name, BytesReference query, List<String> indices, String matchField, List<String> enrichFields) {
this.type = type;
this.name = name;
this.query = query;
this.indices = indices;
this.matchField = matchField;
this.enrichFields = enrichFields;
}
public String getType() {
return type;
}
public String getName() {
return name;
}
public BytesReference getQuery() {
return query;
}
public List<String> getIndices() {
return indices;
}
public String getMatchField() {
return matchField;
}
public List<String> getEnrichFields() {
return enrichFields;
}
}

View File

@ -19,7 +19,6 @@
package org.elasticsearch.client.enrich; package org.elasticsearch.client.enrich;
import org.elasticsearch.client.Validatable; import org.elasticsearch.client.Validatable;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.Strings; import org.elasticsearch.common.Strings;
import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.ToXContentObject; import org.elasticsearch.common.xcontent.ToXContentObject;
@ -36,11 +35,6 @@ import java.util.Objects;
public class PutPolicyRequest implements Validatable, ToXContentObject { public class PutPolicyRequest implements Validatable, ToXContentObject {
static final ParseField QUERY_FIELD = new ParseField("query");
static final ParseField INDICES_FIELD = new ParseField("indices");
static final ParseField MATCH_FIELD_FIELD = new ParseField("match_field");
static final ParseField ENRICH_FIELDS_FIELD = new ParseField("enrich_fields");
private final String name; private final String name;
private final String type; private final String type;
private BytesReference query; private BytesReference query;
@ -110,12 +104,12 @@ public class PutPolicyRequest implements Validatable, ToXContentObject {
{ {
builder.startObject(type); builder.startObject(type);
{ {
builder.field(INDICES_FIELD.getPreferredName(), indices); builder.field(NamedPolicy.INDICES_FIELD.getPreferredName(), indices);
if (query != null) { if (query != null) {
builder.field(QUERY_FIELD.getPreferredName(), asMap(query, builder.contentType())); builder.field(NamedPolicy.QUERY_FIELD.getPreferredName(), asMap(query, builder.contentType()));
} }
builder.field(MATCH_FIELD_FIELD.getPreferredName(), matchField); builder.field(NamedPolicy.MATCH_FIELD_FIELD.getPreferredName(), matchField);
builder.field(ENRICH_FIELDS_FIELD.getPreferredName(), enrichFields); builder.field(NamedPolicy.ENRICH_FIELDS_FIELD.getPreferredName(), enrichFields);
} }
builder.endObject(); builder.endObject();
} }

View File

@ -18,18 +18,13 @@
*/ */
package org.elasticsearch.client; package org.elasticsearch.client;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.core.AcknowledgedResponse; import org.elasticsearch.client.core.AcknowledgedResponse;
import org.elasticsearch.client.enrich.DeletePolicyRequest; import org.elasticsearch.client.enrich.DeletePolicyRequest;
import org.elasticsearch.client.enrich.GetPolicyRequest;
import org.elasticsearch.client.enrich.GetPolicyResponse;
import org.elasticsearch.client.enrich.PutPolicyRequest; import org.elasticsearch.client.enrich.PutPolicyRequest;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.common.xcontent.support.XContentMapValues;
import java.io.IOException;
import java.util.Collections; import java.util.Collections;
import java.util.List;
import java.util.Map;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.is;
@ -43,35 +38,22 @@ public class EnrichIT extends ESRestHighLevelClientTestCase {
AcknowledgedResponse putPolicyResponse = execute(putPolicyRequest, enrichClient::putPolicy, enrichClient::putPolicyAsync); AcknowledgedResponse putPolicyResponse = execute(putPolicyRequest, enrichClient::putPolicy, enrichClient::putPolicyAsync);
assertThat(putPolicyResponse.isAcknowledged(), is(true)); assertThat(putPolicyResponse.isAcknowledged(), is(true));
// TODO: Replace with get policy hlrc code: GetPolicyRequest getPolicyRequest = randomBoolean() ? new GetPolicyRequest("my-policy") : new GetPolicyRequest();
Request getPolicyRequest = new Request("get", "/_enrich/policy/my-policy"); GetPolicyResponse getPolicyResponse = execute(getPolicyRequest, enrichClient::getPolicy, enrichClient::getPolicyAsync);
Response getPolicyResponse = highLevelClient().getLowLevelClient().performRequest(getPolicyRequest); assertThat(getPolicyResponse.getPolicies().size(), equalTo(1));
assertThat(getPolicyResponse.getHttpResponse().getStatusLine().getStatusCode(), equalTo(200)); assertThat(getPolicyResponse.getPolicies().get(0).getType(), equalTo(putPolicyRequest.getType()));
Map<String, Object> responseBody = toMap(getPolicyResponse); assertThat(getPolicyResponse.getPolicies().get(0).getIndices(), equalTo(putPolicyRequest.getIndices()));
List<?> responsePolicies = (List<?>) responseBody.get("policies"); assertThat(getPolicyResponse.getPolicies().get(0).getMatchField(), equalTo(putPolicyRequest.getMatchField()));
assertThat(responsePolicies.size(), equalTo(1)); assertThat(getPolicyResponse.getPolicies().get(0).getEnrichFields(), equalTo(putPolicyRequest.getEnrichFields()));
Map<?, ?> responsePolicy = (Map<?, ?>) responsePolicies.get(0);
assertThat(XContentMapValues.extractValue("match.indices", responsePolicy), equalTo(putPolicyRequest.getIndices()));
assertThat(XContentMapValues.extractValue("match.match_field", responsePolicy), equalTo(putPolicyRequest.getMatchField()));
assertThat(XContentMapValues.extractValue("match.enrich_fields", responsePolicy),
equalTo(putPolicyRequest.getEnrichFields()));
DeletePolicyRequest deletePolicyRequest = new DeletePolicyRequest("my-policy"); DeletePolicyRequest deletePolicyRequest = new DeletePolicyRequest("my-policy");
AcknowledgedResponse deletePolicyResponse = AcknowledgedResponse deletePolicyResponse =
execute(deletePolicyRequest, enrichClient::deletePolicy, enrichClient::deletePolicyAsync); execute(deletePolicyRequest, enrichClient::deletePolicy, enrichClient::deletePolicyAsync);
assertThat(deletePolicyResponse.isAcknowledged(), is(true)); assertThat(deletePolicyResponse.isAcknowledged(), is(true));
// TODO: Replace with get policy hlrc code: getPolicyRequest = new GetPolicyRequest();
getPolicyRequest = new Request("get", "/_enrich/policy"); getPolicyResponse = execute(getPolicyRequest, enrichClient::getPolicy, enrichClient::getPolicyAsync);
getPolicyResponse = highLevelClient().getLowLevelClient().performRequest(getPolicyRequest); assertThat(getPolicyResponse.getPolicies().size(), equalTo(0));
assertThat(getPolicyResponse.getHttpResponse().getStatusLine().getStatusCode(), equalTo(200));
responseBody = toMap(getPolicyResponse);
responsePolicies = (List<?>) responseBody.get("policies");
assertThat(responsePolicies.size(), equalTo(0));
}
private static Map<String, Object> toMap(Response response) throws IOException {
return XContentHelper.convertToMap(JsonXContent.jsonXContent, EntityUtils.toString(response.getEntity()), false);
} }
} }

View File

@ -19,8 +19,10 @@
package org.elasticsearch.client; package org.elasticsearch.client;
import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpPut;
import org.elasticsearch.client.enrich.DeletePolicyRequest; import org.elasticsearch.client.enrich.DeletePolicyRequest;
import org.elasticsearch.client.enrich.GetPolicyRequest;
import org.elasticsearch.client.enrich.PutPolicyRequest; import org.elasticsearch.client.enrich.PutPolicyRequest;
import org.elasticsearch.client.enrich.PutPolicyRequestTests; import org.elasticsearch.client.enrich.PutPolicyRequestTests;
import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.ESTestCase;
@ -50,4 +52,30 @@ public class EnrichRequestConvertersTests extends ESTestCase {
assertThat(result.getEntity(), nullValue()); assertThat(result.getEntity(), nullValue());
} }
public void testGetPolicy() throws Exception {
GetPolicyRequest request = new GetPolicyRequest(randomAlphaOfLength(4));
Request result = EnrichRequestConverters.getPolicy(request);
assertThat(result.getMethod(), equalTo(HttpGet.METHOD_NAME));
assertThat(result.getEndpoint(), equalTo("/_enrich/policy/" + request.getNames().get(0)));
assertThat(result.getParameters().size(), equalTo(0));
assertThat(result.getEntity(), nullValue());
request = new GetPolicyRequest(randomAlphaOfLength(4), randomAlphaOfLength(4));
result = EnrichRequestConverters.getPolicy(request);
assertThat(result.getMethod(), equalTo(HttpGet.METHOD_NAME));
assertThat(result.getEndpoint(), equalTo("/_enrich/policy/" + request.getNames().get(0) + "," + request.getNames().get(1)));
assertThat(result.getParameters().size(), equalTo(0));
assertThat(result.getEntity(), nullValue());
request = new GetPolicyRequest();
result = EnrichRequestConverters.getPolicy(request);
assertThat(result.getMethod(), equalTo(HttpGet.METHOD_NAME));
assertThat(result.getEndpoint(), equalTo("/_enrich/policy"));
assertThat(result.getParameters().size(), equalTo(0));
assertThat(result.getEntity(), nullValue());
}
} }

View File

@ -25,10 +25,15 @@ import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.core.AcknowledgedResponse; import org.elasticsearch.client.core.AcknowledgedResponse;
import org.elasticsearch.client.enrich.DeletePolicyRequest; import org.elasticsearch.client.enrich.DeletePolicyRequest;
import org.elasticsearch.client.enrich.NamedPolicy;
import org.elasticsearch.client.enrich.GetPolicyRequest;
import org.elasticsearch.client.enrich.GetPolicyResponse;
import org.elasticsearch.client.enrich.PutPolicyRequest; import org.elasticsearch.client.enrich.PutPolicyRequest;
import org.junit.After; import org.junit.After;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -143,4 +148,54 @@ public class EnrichDocumentationIT extends ESRestHighLevelClientTestCase {
assertTrue(latch.await(30L, TimeUnit.SECONDS)); assertTrue(latch.await(30L, TimeUnit.SECONDS));
} }
public void testGetPolicy() throws Exception {
RestHighLevelClient client = highLevelClient();
PutPolicyRequest putPolicyRequest = new PutPolicyRequest(
"users-policy", "exact_match", Collections.singletonList("users"),
"email", Arrays.asList("address", "zip", "city", "state"));
client.enrich().putPolicy(putPolicyRequest, RequestOptions.DEFAULT);
// tag::enrich-get-policy-request
GetPolicyRequest getPolicyRequest = new GetPolicyRequest("users-policy");
// end::enrich-get-policy-request
// tag::enrich-get-policy-execute
GetPolicyResponse getPolicyResponse =
client.enrich().getPolicy(getPolicyRequest, RequestOptions.DEFAULT);
// end::enrich-get-policy-execute
// tag::enrich-get-policy-response
List<NamedPolicy> policies = getPolicyResponse.getPolicies(); // <1>
NamedPolicy policy = policies.get(0);
// end::enrich-get-policy-response
// tag::enrich-get-policy-execute-listener
ActionListener<GetPolicyResponse> listener =
new ActionListener<GetPolicyResponse>() {
@Override
public void onResponse(GetPolicyResponse response) { // <1>
List<NamedPolicy> policies = response.getPolicies();
NamedPolicy policy = policies.get(0);
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::enrich-get-policy-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::enrich-get-policy-execute-async
client.enrich().getPolicyAsync(getPolicyRequest,
RequestOptions.DEFAULT, listener); // <1>
// end::enrich-get-policy-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
} }

View File

@ -0,0 +1,95 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.enrich;
import org.elasticsearch.client.AbstractResponseTestCase;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.xpack.core.enrich.EnrichPolicy;
import org.elasticsearch.xpack.core.enrich.action.GetEnrichPolicyAction;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
public class GetPolicyResponseTests extends AbstractResponseTestCase<GetEnrichPolicyAction.Response, GetPolicyResponse> {
@Override
protected GetEnrichPolicyAction.Response createServerTestInstance(XContentType xContentType) {
int numPolicies = randomIntBetween(0, 8);
Map<String, EnrichPolicy> policies = new HashMap<>(numPolicies);
for (int i = 0; i < numPolicies; i++) {
policies.put(randomAlphaOfLength(4), createRandomEnrichPolicy(xContentType));
}
return new GetEnrichPolicyAction.Response(policies);
}
@Override
protected GetPolicyResponse doParseToClientInstance(XContentParser parser) throws IOException {
return GetPolicyResponse.fromXContent(parser);
}
@Override
protected void assertInstances(GetEnrichPolicyAction.Response serverTestInstance, GetPolicyResponse clientInstance) {
assertThat(clientInstance.getPolicies().size(), equalTo(serverTestInstance.getPolicies().size()));
for (int i = 0; i < clientInstance.getPolicies().size(); i++) {
assertThat(clientInstance.getPolicies().get(i).getType(),
equalTo(serverTestInstance.getPolicies().get(i).getPolicy().getType()));
assertThat(clientInstance.getPolicies().get(i).getName(),
equalTo(serverTestInstance.getPolicies().get(i).getName()));
assertThat(clientInstance.getPolicies().get(i).getIndices(),
equalTo(serverTestInstance.getPolicies().get(i).getPolicy().getIndices()));
if (clientInstance.getPolicies().get(i).getQuery() != null) {
assertThat(clientInstance.getPolicies().get(i).getQuery(),
equalTo(serverTestInstance.getPolicies().get(i).getPolicy().getQuery().getQuery()));
} else {
assertThat(serverTestInstance.getPolicies().get(i).getPolicy().getQuery(), nullValue());
}
assertThat(clientInstance.getPolicies().get(i).getMatchField(),
equalTo(serverTestInstance.getPolicies().get(i).getPolicy().getMatchField()));
assertThat(clientInstance.getPolicies().get(i).getEnrichFields(),
equalTo(serverTestInstance.getPolicies().get(i).getPolicy().getEnrichFields()));
}
}
private static EnrichPolicy createRandomEnrichPolicy(XContentType xContentType){
try (XContentBuilder builder = XContentBuilder.builder(xContentType.xContent())) {
builder.startObject();
builder.endObject();
BytesReference querySource = BytesArray.bytes(builder);
return new EnrichPolicy(
randomAlphaOfLength(4),
randomBoolean() ? new EnrichPolicy.QuerySource(querySource, xContentType) : null,
Arrays.asList(generateRandomStringArray(8, 4, false, false)),
randomAlphaOfLength(4),
Arrays.asList(generateRandomStringArray(8, 4, false, false))
);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}

View File

@ -0,0 +1,32 @@
--
:api: enrich-get-policy
:request: GetPolicyRequest
:response: GetPolicyResponse
--
[id="{upid}-{api}"]
=== Get Policy API
[id="{upid}-{api}-request"]
==== Request
The Get Policy API allows to retrieve enrich policies by name
or all policies if no name is provided.
["source","java",subs="attributes,callouts,macros"]
--------------------------------------------------
include-tagged::{doc-tests-file}[{api}-request]
--------------------------------------------------
[id="{upid}-{api}-response"]
==== Response
The returned +{response}+ includes the requested enrich policy.
["source","java",subs="attributes,callouts,macros"]
--------------------------------------------------
include-tagged::{doc-tests-file}[{api}-response]
--------------------------------------------------
<1> The actual enrich policy.
include::../execution.asciidoc[]

View File

@ -604,6 +604,8 @@ The Java High Level REST Client supports the following Enrich APIs:
* <<{upid}-enrich-put-policy>> * <<{upid}-enrich-put-policy>>
* <<{upid}-enrich-delete-policy>> * <<{upid}-enrich-delete-policy>>
* <<{upid}-enrich-get-policy>>
include::enrich/put_policy.asciidoc[] include::enrich/put_policy.asciidoc[]
include::enrich/delete_policy.asciidoc[] include::enrich/delete_policy.asciidoc[]
include::enrich/get_policy.asciidoc[]