Skip to content

Commit

Permalink
[Issue 13019][es-sink] Support event-time-based index name in ES Sink (
Browse files Browse the repository at this point in the history
…#14383)

Fixes #13019

### Motivation

As described in the original issue, it's a common request to write data to event-time-based indices in logs and metrics use cases, therefore it would be very helpful to have builtin support in the ES sink.

### Modifications

*Describe the modifications you've done.*

### Verifying this change

- [ ] Make sure that the change passes the CI checks.
This change added tests and can be verified as follows:
  - *Added test cases for index name formatter*
  • Loading branch information
fantapsody authored Feb 28, 2022
1 parent 330fcb9 commit 21c3a0b
Show file tree
Hide file tree
Showing 6 changed files with 210 additions and 21 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
Expand Down Expand Up @@ -125,9 +124,15 @@ public class ElasticSearchClient implements AutoCloseable {
final ConcurrentMap<DocWriteRequest<?>, Record> records = new ConcurrentHashMap<>();
final AtomicReference<Exception> irrecoverableError = new AtomicReference<>();
final ScheduledExecutorService executorService;
private final IndexNameFormatter indexNameFormatter;

ElasticSearchClient(ElasticSearchConfig elasticSearchConfig) {
this.config = elasticSearchConfig;
if (this.config.getIndexName() != null) {
this.indexNameFormatter = new IndexNameFormatter(this.config.getIndexName());
} else {
this.indexNameFormatter = null;
}
this.configCallback = new ConfigCallback();
this.backoffRetry = new RandomExponentialRetry(elasticSearchConfig.getMaxRetryTimeInSec());
if (!config.isBulkEnabled()) {
Expand Down Expand Up @@ -254,7 +259,7 @@ void hasIrrecoverableError(BulkItemResponse bulkItemResponse) throws Exception {
}

IndexRequest makeIndexRequest(Record<GenericObject> record, Pair<String, String> idAndDoc) throws IOException {
IndexRequest indexRequest = Requests.indexRequest(indexName(record.getTopicName()));
IndexRequest indexRequest = Requests.indexRequest(indexName(record));
if (!Strings.isNullOrEmpty(idAndDoc.getLeft())) {
indexRequest.id(idAndDoc.getLeft());
}
Expand All @@ -264,16 +269,16 @@ IndexRequest makeIndexRequest(Record<GenericObject> record, Pair<String, String>
}

DeleteRequest makeDeleteRequest(Record<GenericObject> record, String id) throws IOException {
DeleteRequest deleteRequest = Requests.deleteRequest(indexName(record.getTopicName()));
DeleteRequest deleteRequest = Requests.deleteRequest(indexName(record));
deleteRequest.id(id);
deleteRequest.type(config.getTypeName());
return deleteRequest;
}

public void bulkIndex(Record record, Pair<String, String> idAndDoc) throws Exception {
public void bulkIndex(Record<GenericObject> record, Pair<String, String> idAndDoc) throws Exception {
try {
checkNotFailed();
checkIndexExists(record.getTopicName());
checkIndexExists(record);
IndexRequest indexRequest = makeIndexRequest(record, idAndDoc);
records.put(indexRequest, record);
bulkProcessor.add(indexRequest);
Expand All @@ -294,7 +299,7 @@ public void bulkIndex(Record record, Pair<String, String> idAndDoc) throws Excep
public boolean indexDocument(Record<GenericObject> record, Pair<String, String> idAndDoc) throws Exception {
try {
checkNotFailed();
checkIndexExists(record.getTopicName());
checkIndexExists(record);
IndexResponse indexResponse = client.index(makeIndexRequest(record, idAndDoc), RequestOptions.DEFAULT);
if (indexResponse.getResult().equals(DocWriteResponse.Result.CREATED)
|| indexResponse.getResult().equals(DocWriteResponse.Result.UPDATED)) {
Expand All @@ -314,7 +319,7 @@ public boolean indexDocument(Record<GenericObject> record, Pair<String, String>
public void bulkDelete(Record<GenericObject> record, String id) throws Exception {
try {
checkNotFailed();
checkIndexExists(record.getTopicName());
checkIndexExists(record);
DeleteRequest deleteRequest = makeDeleteRequest(record, id);
records.put(deleteRequest, record);
bulkProcessor.add(deleteRequest);
Expand All @@ -335,7 +340,7 @@ public void bulkDelete(Record<GenericObject> record, String id) throws Exception
public boolean deleteDocument(Record<GenericObject> record, String id) throws Exception {
try {
checkNotFailed();
checkIndexExists(record.getTopicName());
checkIndexExists(record);
DeleteResponse deleteResponse = client.delete(makeDeleteRequest(record, id), RequestOptions.DEFAULT);
log.debug("delete result=" + deleteResponse.getResult());
if (deleteResponse.getResult().equals(DocWriteResponse.Result.DELETED)
Expand Down Expand Up @@ -384,11 +389,11 @@ private void checkNotFailed() throws Exception {
}
}

private void checkIndexExists(Optional<String> topicName) throws IOException {
private void checkIndexExists(Record<GenericObject> record) throws IOException {
if (!config.isCreateIndexIfNeeded()) {
return;
}
String indexName = indexName(topicName);
String indexName = indexName(record);
if (!indexCache.contains(indexName)) {
synchronized (this) {
if (!indexCache.contains(indexName)) {
Expand All @@ -399,15 +404,15 @@ private void checkIndexExists(Optional<String> topicName) throws IOException {
}
}

private String indexName(Optional<String> topicName) throws IOException {
if (config.getIndexName() != null) {
private String indexName(Record<GenericObject> record) throws IOException {
if (indexNameFormatter != null) {
// Use the configured indexName if provided.
return config.getIndexName();
return indexNameFormatter.indexName(record);
}
if (!topicName.isPresent()) {
if (!record.getTopicName().isPresent()) {
throw new IOException("Elasticsearch index name configuration and topic name are empty");
}
return topicToIndexName(topicName.get());
return topicToIndexName(record.getTopicName().get());
}

@VisibleForTesting
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
import java.io.IOException;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import java.util.Map;
import lombok.Data;
import lombok.experimental.Accessors;
Expand All @@ -50,7 +49,11 @@ public class ElasticSearchConfig implements Serializable {
@FieldDoc(
required = false,
defaultValue = "",
help = "The index name that the connector writes messages to, the default is the topic name"
help = "The index name to which the connector writes messages. The default value is the topic name."
+ " It accepts date formats in the name to support event time based index with"
+ " the pattern %{+<date-format>}. For example, suppose the event time of the record"
+ " is 1645182000000L, the indexName is \"logs-%{+yyyy-MM-dd}\", then the formatted"
+ " index name would be \"logs-2022-02-18\"."
)
private String indexName;

Expand Down Expand Up @@ -273,9 +276,8 @@ public void validate() {

if (StringUtils.isNotEmpty(indexName) && createIndexIfNeeded) {
// see https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html#indices-create-api-path-params
if (!indexName.toLowerCase(Locale.ROOT).equals(indexName)) {
throw new IllegalArgumentException("indexName should be lowercase only.");
}
// date format may contain upper cases, so we need to valid against parsed index name
IndexNameFormatter.validate(indexName);
if (indexName.startsWith("-") || indexName.startsWith("_") || indexName.startsWith("+")) {
throw new IllegalArgumentException("indexName start with an invalid character.");
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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.apache.pulsar.io.elasticsearch;

import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.pulsar.client.api.schema.GenericObject;
import org.apache.pulsar.functions.api.Record;

/**
* A class that helps to generate the time-based index names.
*
* The formatter finds the pattern %{+<date-format>} in the format string
* and replace them with strings that are formatted from the event time of the record
* using <date-format>. The format follows the rules of {@link java.time.format.DateTimeFormatter}.
*
* For example, suppose the event time of the record is 1645182000000L, the indexName
* is "logs-%{+yyyy-MM-dd}", then the formatted index name would be "logs-2022-02-18".
*/
public class IndexNameFormatter {
private static final Pattern PATTERN_FIELD_REF = Pattern.compile("%\\{\\+(.+?)}");

private final String indexNameFormat;
private final List<String> segments;
private final List<DateTimeFormatter> dateTimeFormatters;

public IndexNameFormatter(String indexNameFormat) {
this.indexNameFormat = indexNameFormat;

Pair<List<String>, List<DateTimeFormatter>> parsed = parseFormat(indexNameFormat);
this.segments = parsed.getKey();
this.dateTimeFormatters = parsed.getRight();
}

static Pair<List<String>, List<DateTimeFormatter>> parseFormat(String format) {
List<String> segments = new ArrayList<>();
List<DateTimeFormatter> formatters = new ArrayList<>();
Matcher matcher = PATTERN_FIELD_REF.matcher(format);
int pos = 0;
while (matcher.find()) {
segments.add(format.substring(pos, matcher.start()));
formatters.add(DateTimeFormatter.ofPattern(matcher.group(1))
.withLocale(Locale.ENGLISH)
.withZone(ZoneId.of("UTC")));
pos = matcher.end();
}
segments.add(format.substring(pos));
return Pair.of(segments, formatters);
}

static void validate(String format) {
Pair<List<String>, List<DateTimeFormatter>> parsed = parseFormat(format);
for (String s : parsed.getLeft()) {
if (!s.toLowerCase(Locale.ROOT).equals(s)) {
throw new IllegalArgumentException("indexName should be lowercase only.");
}
}
}

public String indexName(Record<GenericObject> record) {
if (this.dateTimeFormatters.isEmpty()) {
return this.indexNameFormat;
}
Instant eventTime = Instant.ofEpochMilli(record.getEventTime()
.orElseThrow(() -> new IllegalStateException("No event time in record")));
StringBuilder builder = new StringBuilder(this.segments.get(0));

for (int i = 0; i < dateTimeFormatters.size(); i++) {
builder.append(dateTimeFormatters.get(i).format(eventTime));
builder.append(this.segments.get(i + 1));
}

return builder.toString();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,22 @@ public void testIndexRequest() throws Exception {
IndexRequest request = client.makeIndexRequest(record, Pair.of("1", "{ \"a\":1}"));
assertEquals(request.index(), topicName);
}
String indexBase = "myindex-" + UUID.randomUUID();
index = indexBase + "-%{+yyyy-MM-dd}";
try (ElasticSearchClient client = new ElasticSearchClient(new ElasticSearchConfig()
.setElasticSearchUrl("http://" + container.getHttpHostAddress())
.setIndexName(index))) {
assertThrows(IllegalStateException.class, () -> {
client.makeIndexRequest(record, Pair.of("1", "{ \"a\":1}"));
});
}
when (record.getEventTime()).thenReturn(Optional.of(1645182000000L));
try (ElasticSearchClient client = new ElasticSearchClient(new ElasticSearchConfig()
.setElasticSearchUrl("http://" + container.getHttpHostAddress())
.setIndexName(index))) {
IndexRequest request = client.makeIndexRequest(record, Pair.of("1", "{ \"a\":1}"));
assertEquals(request.index(), indexBase + "-2022-02-18");
}
}

@Test
Expand All @@ -121,6 +137,22 @@ public void testDeleteRequest() throws Exception {
DeleteRequest request = client.makeDeleteRequest(record, "1");
assertEquals(request.index(), topicName);
}
String indexBase = "myindex-" + UUID.randomUUID();
index = indexBase + "-%{+yyyy-MM-dd}";
try (ElasticSearchClient client = new ElasticSearchClient(new ElasticSearchConfig()
.setElasticSearchUrl("http://" + container.getHttpHostAddress())
.setIndexName(index))) {
assertThrows(IllegalStateException.class, () -> {
client.makeDeleteRequest(record, "1");
});
}
when (record.getEventTime()).thenReturn(Optional.of(1645182000000L));
try (ElasticSearchClient client = new ElasticSearchClient(new ElasticSearchConfig()
.setElasticSearchUrl("http://" + container.getHttpHostAddress())
.setIndexName(index))) {
DeleteRequest request = client.makeDeleteRequest(record, "1");
assertEquals(request.index(), indexBase + "-2022-02-18");
}
}

@Test
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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.apache.pulsar.io.elasticsearch;

import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;

import java.util.Optional;
import org.apache.pulsar.functions.api.Record;
import org.mockito.Mockito;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class IndexNameFormatterTest {
@DataProvider(name = "indexFormats")
public Object[][] indexPatternTestData() {
return new Object[][]{
new Object[] {"test", "test"},
new Object[] {"test-%{yyyy}", "test-%{yyyy}"},
new Object[] {"test-%{+yyyy}", "test-2022"},
new Object[] {"test-%{+yyyy-MM}", "test-2022-02"},
new Object[] {"test-%{+yyyy-MM-dd}", "test-2022-02-18"},
new Object[] {"test-%{+yyyy-MM-dd}-abc", "test-2022-02-18-abc"},
new Object[] {"%{+yyyy-MM-dd}-abc", "2022-02-18-abc"},
new Object[] {"%{+yyyy}/%{+MM-dd}", "2022/02-18"},
};
}

@Test(dataProvider = "indexFormats")
public void testIndexFormats(String format, String result) {
Record record = Mockito.mock(Record.class);
when(record.getEventTime()).thenReturn(Optional.of(1645182000000L));
IndexNameFormatter formatter = new IndexNameFormatter(format);
assertEquals(formatter.indexName(record), result);
}
}
2 changes: 1 addition & 1 deletion site2/website-next/docs/io-elasticsearch-sink.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ The configuration of the Elasticsearch sink connector has the following properti
| Name | Type|Required | Default | Description
|------|----------|----------|---------|-------------|
| `elasticSearchUrl` | String| true |" " (empty string)| The URL of elastic search cluster to which the connector connects. |
| `indexName` | String| true |" " (empty string)| The index name to which the connector writes messages. |
| `indexName` | String| true |" " (empty string)| The index name to which the connector writes messages. The default value is the topic name. It accepts date formats in the name to support event time based index with the pattern `%{+<date-format>}`. For example, suppose the event time of the record is 1645182000000L, the indexName is `logs-%{+yyyy-MM-dd}`, then the formatted index name would be `logs-2022-02-18`. |
| `schemaEnable` | Boolean | false | false | Turn on the Schema Aware mode. |
| `createIndexIfNeeded` | Boolean | false | false | Manage index if missing. |
| `maxRetries` | Integer | false | 1 | The maximum number of retries for elasticsearch requests. Use -1 to disable it. |
Expand Down

0 comments on commit 21c3a0b

Please sign in to comment.