Skip to content

Commit 3c7f463

Browse files
authored
Add enrich processor (#41532)
The enrich processor performs a lookup in a locally allocated enrich index shard using a field value from the document being enriched. If there is a match then the _source of the enrich document is fetched. The document being enriched then gets the decorate values from the enrich document based on the configured decorate fields in the pipeline. Note that the usage of the _source field is temporary until the enrich source field that is part of #41521 is merged into the enrich branch. Using the _source field involves significant decompression which not desired for enrich use cases. The policy contains the information what field in the enrich index to query and what fields are available to decorate a document being enriched with. The enrich processor has the following configuration options: * `policy_name` - the name of the policy this processor should use * `enrich_key` - the field in the document being enriched that holds to lookup value * `ignore_missing` - Whether to allow the key field to be missing * `enrich_values` - a list of fields to decorate the document being enriched with. Each entry holds a source field and a target field. The source field indicates what decorate field to use that is available in the policy. The target field controls the field name to use in the document being enriched. The source and target fields can be the same. Example pipeline config: ``` { "processors": [ { "policy_name": "my_policy", "enrich_key": "host_name", "enrich_values": [ { "source": "globalRank", "target": "global_rank" } ] } ] } ``` In the above example documents are being enriched with a global rank value. For each document that has match in the enrich index based on its host_name field, the document gets an global rank field value, which is fetched from the `globalRank` field in the enrich index and saved as `global_rank` in the document being enriched. This is PR is part one of #41521
1 parent 8c8e3e0 commit 3c7f463

File tree

7 files changed

+743
-2
lines changed

7 files changed

+743
-2
lines changed

x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/enrich/EnrichPolicy.java

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
*/
2929
public final class EnrichPolicy implements Writeable, ToXContentFragment {
3030

31-
static final String EXACT_MATCH_TYPE = "exact_match";
31+
public static final String EXACT_MATCH_TYPE = "exact_match";
3232
public static final String[] SUPPORTED_POLICY_TYPES = new String[]{EXACT_MATCH_TYPE};
3333

3434
static final ParseField TYPE = new ParseField("type");
@@ -125,6 +125,11 @@ public String getSchedule() {
125125
return schedule;
126126
}
127127

128+
public String getAliasName(String policyName) {
129+
// #41553 (list policy api) will add name to policy, so that we don't have to provide the name via a parameter.
130+
return ".enrich-" + policyName;
131+
}
132+
128133
@Override
129134
public void writeTo(StreamOutput out) throws IOException {
130135
out.writeString(type);
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
/*
2+
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
3+
* or more contributor license agreements. Licensed under the Elastic License;
4+
* you may not use this file except in compliance with the Elastic License.
5+
*/
6+
package org.elasticsearch.xpack.enrich;
7+
8+
import org.apache.http.entity.ByteArrayEntity;
9+
import org.apache.http.entity.ContentType;
10+
import org.apache.http.util.EntityUtils;
11+
import org.elasticsearch.client.Request;
12+
import org.elasticsearch.client.Response;
13+
import org.elasticsearch.common.xcontent.XContentBuilder;
14+
import org.elasticsearch.common.xcontent.XContentHelper;
15+
import org.elasticsearch.common.xcontent.XContentType;
16+
import org.elasticsearch.common.xcontent.json.JsonXContent;
17+
import org.elasticsearch.test.rest.ESRestTestCase;
18+
19+
import java.io.ByteArrayOutputStream;
20+
import java.io.IOException;
21+
import java.util.Map;
22+
23+
import static org.hamcrest.Matchers.equalTo;
24+
25+
public class EnrichIT extends ESRestTestCase {
26+
27+
// TODO: update this test when policy runner is ready
28+
public void testBasicFlow() throws Exception {
29+
// Create the policy:
30+
Request putPolicyRequest = new Request("PUT", "/_enrich/policy/my_policy");
31+
putPolicyRequest.setJsonEntity("{\"type\": \"exact_match\",\"index_pattern\": \"my-index*\", \"enrich_key\": \"host\", " +
32+
"\"enrich_values\": [\"globalRank\", \"tldRank\", \"tld\"], \"schedule\": \"0 5 * * *\"}");
33+
assertOK(client().performRequest(putPolicyRequest));
34+
35+
// Add a single enrich document for now and then refresh:
36+
Request indexRequest = new Request("PUT", "/.enrich-my_policy/_doc/elastic.co");
37+
XContentBuilder document = XContentBuilder.builder(XContentType.SMILE.xContent());
38+
document.startObject();
39+
document.field("host", "elastic.co");
40+
document.field("globalRank", 25);
41+
document.field("tldRank", 7);
42+
document.field("tld", "co");
43+
document.endObject();
44+
document.close();
45+
ByteArrayOutputStream out = (ByteArrayOutputStream) document.getOutputStream();
46+
indexRequest.setEntity(new ByteArrayEntity(out.toByteArray(), ContentType.create("application/smile")));
47+
assertOK(client().performRequest(indexRequest));
48+
Request refreshRequest = new Request("POST", "/.enrich-my_policy/_refresh");
49+
assertOK(client().performRequest(refreshRequest));
50+
51+
// Create pipeline
52+
Request putPipelineRequest = new Request("PUT", "/_ingest/pipeline/my_pipeline");
53+
putPipelineRequest.setJsonEntity("{\"processors\":[" +
54+
"{\"enrich\":{\"policy_name\":\"my_policy\",\"enrich_key\":\"host\",\"enrich_values\":[" +
55+
"{\"source\":\"globalRank\",\"target\":\"global_rank\"}," +
56+
"{\"source\":\"tldRank\",\"target\":\"tld_rank\"}" +
57+
"]}}" +
58+
"]}");
59+
assertOK(client().performRequest(putPipelineRequest));
60+
61+
// Index document using pipeline with enrich processor:
62+
indexRequest = new Request("PUT", "/my-index/_doc/1");
63+
indexRequest.addParameter("pipeline", "my_pipeline");
64+
indexRequest.setJsonEntity("{\"host\": \"elastic.co\"}");
65+
assertOK(client().performRequest(indexRequest));
66+
67+
// Check if document has been enriched
68+
Request getRequest = new Request("GET", "/my-index/_doc/1");
69+
Map<String, Object> response = toMap(client().performRequest(getRequest));
70+
Map<?, ?> _source = (Map<?, ?>) response.get("_source");
71+
assertThat(_source.size(), equalTo(3));
72+
assertThat(_source.get("host"), equalTo("elastic.co"));
73+
assertThat(_source.get("global_rank"), equalTo(25));
74+
assertThat(_source.get("tld_rank"), equalTo(7));
75+
}
76+
77+
private static Map<String, Object> toMap(Response response) throws IOException {
78+
return toMap(EntityUtils.toString(response.getEntity()));
79+
}
80+
81+
private static Map<String, Object> toMap(String response) {
82+
return XContentHelper.convertToMap(JsonXContent.jsonXContent, response, false);
83+
}
84+
85+
}

x-pack/plugin/enrich/src/main/java/org/elasticsearch/xpack/enrich/EnrichPlugin.java

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,10 @@
77

88
import org.elasticsearch.action.ActionRequest;
99
import org.elasticsearch.action.ActionResponse;
10+
import org.elasticsearch.cluster.ClusterState;
1011
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
1112
import org.elasticsearch.cluster.metadata.MetaData;
13+
import org.elasticsearch.cluster.service.ClusterService;
1214
import org.elasticsearch.cluster.node.DiscoveryNodes;
1315
import org.elasticsearch.common.ParseField;
1416
import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
@@ -31,6 +33,7 @@
3133
import java.util.Collections;
3234
import java.util.List;
3335
import java.util.Map;
36+
import java.util.concurrent.atomic.AtomicReference;
3437
import java.util.function.Supplier;
3538

3639
import static java.util.Collections.emptyList;
@@ -48,7 +51,14 @@ public EnrichPlugin(final Settings settings) {
4851

4952
@Override
5053
public Map<String, Processor.Factory> getProcessors(Processor.Parameters parameters) {
51-
return Collections.emptyMap();
54+
final ClusterService clusterService = parameters.ingestService.getClusterService();
55+
// Pipelines are created from cluster state update thead and calling ClusterService#state() from that thead is illegal
56+
// (because the current cluster state update is in progress)
57+
// So with the below atomic reference we keep track of the latest updated cluster state:
58+
AtomicReference<ClusterState> reference = new AtomicReference<>();
59+
clusterService.addStateApplier(event -> reference.set(event.state()));
60+
61+
return Map.of(EnrichProcessorFactory.TYPE, new EnrichProcessorFactory(reference::get, parameters.localShardSearcher));
5262
}
5363

5464
public List<ActionHandler<? extends ActionRequest, ? extends ActionResponse>> getActions() {
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
/*
2+
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
3+
* or more contributor license agreements. Licensed under the Elastic License;
4+
* you may not use this file except in compliance with the Elastic License.
5+
*/
6+
package org.elasticsearch.xpack.enrich;
7+
8+
import org.elasticsearch.cluster.ClusterState;
9+
import org.elasticsearch.index.engine.Engine;
10+
import org.elasticsearch.ingest.ConfigurationUtils;
11+
import org.elasticsearch.ingest.Processor;
12+
import org.elasticsearch.xpack.core.enrich.EnrichPolicy;
13+
14+
import java.util.List;
15+
import java.util.Map;
16+
import java.util.function.Function;
17+
import java.util.function.Supplier;
18+
import java.util.stream.Collectors;
19+
20+
final class EnrichProcessorFactory implements Processor.Factory {
21+
22+
static final String TYPE = "enrich";
23+
24+
private final Function<String, EnrichPolicy> policyLookup;
25+
private final Function<String, Engine.Searcher> searchProvider;
26+
27+
EnrichProcessorFactory(Supplier<ClusterState> clusterStateSupplier,
28+
Function<String, Engine.Searcher> searchProvider) {
29+
this.policyLookup = policyName -> EnrichStore.getPolicy(policyName, clusterStateSupplier.get());
30+
this.searchProvider = searchProvider;
31+
}
32+
33+
@Override
34+
public Processor create(Map<String, Processor.Factory> processorFactories, String tag, Map<String, Object> config) throws Exception {
35+
String policyName = ConfigurationUtils.readStringProperty(TYPE, tag, config, "policy_name");
36+
EnrichPolicy policy = policyLookup.apply(policyName);
37+
if (policy == null) {
38+
throw new IllegalArgumentException("policy [" + policyName + "] does not exists");
39+
}
40+
41+
String enrichKey = ConfigurationUtils.readStringProperty(TYPE, tag, config, "enrich_key", policy.getEnrichKey());
42+
boolean ignoreMissing = ConfigurationUtils.readBooleanProperty(TYPE, tag, config, "ignore_missing", false);
43+
44+
final List<EnrichSpecification> specifications;
45+
final List<Map<?, ?>> specificationConfig = ConfigurationUtils.readList(TYPE, tag, config, "enrich_values");
46+
specifications = specificationConfig.stream()
47+
// TODO: Add templating support in enrich_values source and target options
48+
.map(entry -> new EnrichSpecification((String) entry.get("source"), (String) entry.get("target")))
49+
.collect(Collectors.toList());
50+
51+
for (EnrichSpecification specification : specifications) {
52+
if (policy.getEnrichValues().contains(specification.sourceField) == false) {
53+
throw new IllegalArgumentException("source field [" + specification.sourceField + "] does not exist in policy [" +
54+
policyName + "]");
55+
}
56+
}
57+
58+
switch (policy.getType()) {
59+
case EnrichPolicy.EXACT_MATCH_TYPE:
60+
return new ExactMatchProcessor(tag, policyLookup, searchProvider, policyName, enrichKey, ignoreMissing, specifications);
61+
default:
62+
throw new IllegalArgumentException("unsupported policy type [" + policy.getType() + "]");
63+
}
64+
}
65+
66+
static final class EnrichSpecification {
67+
68+
final String sourceField;
69+
final String targetField;
70+
71+
EnrichSpecification(String sourceField, String targetField) {
72+
this.sourceField = sourceField;
73+
this.targetField = targetField;
74+
}
75+
}
76+
77+
}
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
/*
2+
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
3+
* or more contributor license agreements. Licensed under the Elastic License;
4+
* you may not use this file except in compliance with the Elastic License.
5+
*/
6+
package org.elasticsearch.xpack.enrich;
7+
8+
import org.apache.lucene.document.Document;
9+
import org.apache.lucene.index.LeafReader;
10+
import org.apache.lucene.index.PostingsEnum;
11+
import org.apache.lucene.index.Terms;
12+
import org.apache.lucene.index.TermsEnum;
13+
import org.apache.lucene.util.BytesRef;
14+
import org.elasticsearch.common.bytes.BytesArray;
15+
import org.elasticsearch.common.bytes.BytesReference;
16+
import org.elasticsearch.common.xcontent.XContentHelper;
17+
import org.elasticsearch.common.xcontent.XContentType;
18+
import org.elasticsearch.index.engine.Engine;
19+
import org.elasticsearch.index.mapper.SourceFieldMapper;
20+
import org.elasticsearch.ingest.AbstractProcessor;
21+
import org.elasticsearch.ingest.IngestDocument;
22+
import org.elasticsearch.xpack.core.enrich.EnrichPolicy;
23+
import org.elasticsearch.xpack.enrich.EnrichProcessorFactory.EnrichSpecification;
24+
25+
import java.util.List;
26+
import java.util.Map;
27+
import java.util.Set;
28+
import java.util.function.Function;
29+
30+
final class ExactMatchProcessor extends AbstractProcessor {
31+
32+
private final Function<String, EnrichPolicy> policyLookup;
33+
private final Function<String, Engine.Searcher> searchProvider;
34+
35+
private final String policyName;
36+
private final String enrichKey;
37+
private final boolean ignoreMissing;
38+
private final List<EnrichSpecification> specifications;
39+
40+
ExactMatchProcessor(String tag,
41+
Function<String, EnrichPolicy> policyLookup,
42+
Function<String, Engine.Searcher> searchProvider,
43+
String policyName,
44+
String enrichKey,
45+
boolean ignoreMissing,
46+
List<EnrichSpecification> specifications) {
47+
super(tag);
48+
this.policyLookup = policyLookup;
49+
this.searchProvider = searchProvider;
50+
this.policyName = policyName;
51+
this.enrichKey = enrichKey;
52+
this.ignoreMissing = ignoreMissing;
53+
this.specifications = specifications;
54+
}
55+
56+
@Override
57+
public IngestDocument execute(IngestDocument ingestDocument) throws Exception {
58+
final EnrichPolicy policy = policyLookup.apply(policyName);
59+
if (policy == null) {
60+
throw new IllegalArgumentException("policy [" + policyName + "] does not exists");
61+
}
62+
63+
final String value = ingestDocument.getFieldValue(enrichKey, String.class, ignoreMissing);
64+
if (value == null) {
65+
return ingestDocument;
66+
}
67+
68+
// TODO: re-use the engine searcher between enriching documents from the same write request
69+
try (Engine.Searcher engineSearcher = searchProvider.apply(policy.getAliasName(policyName))) {
70+
if (engineSearcher.getDirectoryReader().leaves().size() == 0) {
71+
return ingestDocument;
72+
} else if (engineSearcher.getDirectoryReader().leaves().size() != 1) {
73+
throw new IllegalStateException("enrich index must have exactly a single segment");
74+
}
75+
76+
final LeafReader leafReader = engineSearcher.getDirectoryReader().leaves().get(0).reader();
77+
final Terms terms = leafReader.terms(policy.getEnrichKey());
78+
if (terms == null) {
79+
throw new IllegalStateException("enrich key field [" + policy.getEnrichKey() + "] does not exist");
80+
}
81+
82+
final TermsEnum tenum = terms.iterator();
83+
if (tenum.seekExact(new BytesRef(value))) {
84+
PostingsEnum penum = tenum.postings(null, PostingsEnum.NONE);
85+
final int docId = penum.nextDoc();
86+
assert docId != PostingsEnum.NO_MORE_DOCS : "no matching doc id for [" + enrichKey + "]";
87+
assert penum.nextDoc() == PostingsEnum.NO_MORE_DOCS : "more than one doc id matching for [" + enrichKey + "]";
88+
89+
// TODO: The use of _source is temporarily until enrich source field mapper has been added (see PR #41521)
90+
Document document = leafReader.document(docId, Set.of(SourceFieldMapper.NAME));
91+
BytesRef source = document.getBinaryValue(SourceFieldMapper.NAME);
92+
assert source != null;
93+
94+
final BytesReference encoded = new BytesArray(source);
95+
final Map<String, Object> decoded =
96+
XContentHelper.convertToMap(encoded, false, XContentType.SMILE).v2();
97+
for (EnrichSpecification specification : specifications) {
98+
Object enrichValue = decoded.get(specification.sourceField);
99+
// TODO: add support over overwrite option (like in SetProcessor)
100+
ingestDocument.setFieldValue(specification.targetField, enrichValue);
101+
}
102+
}
103+
}
104+
return ingestDocument;
105+
}
106+
107+
@Override
108+
public String getType() {
109+
return EnrichProcessorFactory.TYPE;
110+
}
111+
112+
String getPolicyName() {
113+
return policyName;
114+
}
115+
116+
String getEnrichKey() {
117+
return enrichKey;
118+
}
119+
120+
boolean isIgnoreMissing() {
121+
return ignoreMissing;
122+
}
123+
124+
List<EnrichSpecification> getSpecifications() {
125+
return specifications;
126+
}
127+
}

0 commit comments

Comments
 (0)