This is an automated email from the ASF dual-hosted git repository.

guangning pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/pulsar.git


The following commit(s) were added to refs/heads/master by this push:
     new 21c3a0b  [Issue 13019][es-sink] Support event-time-based index name in 
ES Sink (#14383)
21c3a0b is described below

commit 21c3a0b5c93fd30fd458fbab818d059fef4fd8ba
Author: Yang Yang <yy...@streamnative.io>
AuthorDate: Mon Feb 28 11:34:15 2022 +0800

    [Issue 13019][es-sink] Support event-time-based index name in ES Sink 
(#14383)
    
    Fixes https://github.com/apache/pulsar/issues/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*
---
 .../io/elasticsearch/ElasticSearchClient.java      | 35 ++++----
 .../io/elasticsearch/ElasticSearchConfig.java      | 12 +--
 .../io/elasticsearch/IndexNameFormatter.java       | 98 ++++++++++++++++++++++
 .../io/elasticsearch/ElasticSearchClientTests.java | 32 +++++++
 .../io/elasticsearch/IndexNameFormatterTest.java   | 52 ++++++++++++
 site2/website-next/docs/io-elasticsearch-sink.md   |  2 +-
 6 files changed, 210 insertions(+), 21 deletions(-)

diff --git 
a/pulsar-io/elastic-search/src/main/java/org/apache/pulsar/io/elasticsearch/ElasticSearchClient.java
 
b/pulsar-io/elastic-search/src/main/java/org/apache/pulsar/io/elasticsearch/ElasticSearchClient.java
index 78b8c86..25c0688 100644
--- 
a/pulsar-io/elastic-search/src/main/java/org/apache/pulsar/io/elasticsearch/ElasticSearchClient.java
+++ 
b/pulsar-io/elastic-search/src/main/java/org/apache/pulsar/io/elasticsearch/ElasticSearchClient.java
@@ -35,7 +35,6 @@ import java.util.HashMap;
 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;
@@ -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()) {
@@ -254,7 +259,7 @@ public class ElasticSearchClient implements AutoCloseable {
     }
 
     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());
         }
@@ -264,16 +269,16 @@ public class ElasticSearchClient implements AutoCloseable 
{
     }
 
     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);
@@ -294,7 +299,7 @@ public class ElasticSearchClient implements AutoCloseable {
     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)) {
@@ -314,7 +319,7 @@ public class ElasticSearchClient implements AutoCloseable {
     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);
@@ -335,7 +340,7 @@ public class ElasticSearchClient implements AutoCloseable {
     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)
@@ -384,11 +389,11 @@ public class ElasticSearchClient implements AutoCloseable 
{
         }
     }
 
-    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)) {
@@ -399,15 +404,15 @@ public class ElasticSearchClient implements AutoCloseable 
{
         }
     }
 
-    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
diff --git 
a/pulsar-io/elastic-search/src/main/java/org/apache/pulsar/io/elasticsearch/ElasticSearchConfig.java
 
b/pulsar-io/elastic-search/src/main/java/org/apache/pulsar/io/elasticsearch/ElasticSearchConfig.java
index 50348a1..44cdee9 100644
--- 
a/pulsar-io/elastic-search/src/main/java/org/apache/pulsar/io/elasticsearch/ElasticSearchConfig.java
+++ 
b/pulsar-io/elastic-search/src/main/java/org/apache/pulsar/io/elasticsearch/ElasticSearchConfig.java
@@ -24,7 +24,6 @@ import java.io.File;
 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;
@@ -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;
 
@@ -273,9 +276,8 @@ public class ElasticSearchConfig implements Serializable {
 
         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.");
             }
diff --git 
a/pulsar-io/elastic-search/src/main/java/org/apache/pulsar/io/elasticsearch/IndexNameFormatter.java
 
b/pulsar-io/elastic-search/src/main/java/org/apache/pulsar/io/elasticsearch/IndexNameFormatter.java
new file mode 100644
index 0000000..d176fea
--- /dev/null
+++ 
b/pulsar-io/elastic-search/src/main/java/org/apache/pulsar/io/elasticsearch/IndexNameFormatter.java
@@ -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();
+    }
+}
diff --git 
a/pulsar-io/elastic-search/src/test/java/org/apache/pulsar/io/elasticsearch/ElasticSearchClientTests.java
 
b/pulsar-io/elastic-search/src/test/java/org/apache/pulsar/io/elasticsearch/ElasticSearchClientTests.java
index 41bbe22..278a7cd 100644
--- 
a/pulsar-io/elastic-search/src/test/java/org/apache/pulsar/io/elasticsearch/ElasticSearchClientTests.java
+++ 
b/pulsar-io/elastic-search/src/test/java/org/apache/pulsar/io/elasticsearch/ElasticSearchClientTests.java
@@ -102,6 +102,22 @@ public class ElasticSearchClientTests {
             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
@@ -121,6 +137,22 @@ public class ElasticSearchClientTests {
             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
diff --git 
a/pulsar-io/elastic-search/src/test/java/org/apache/pulsar/io/elasticsearch/IndexNameFormatterTest.java
 
b/pulsar-io/elastic-search/src/test/java/org/apache/pulsar/io/elasticsearch/IndexNameFormatterTest.java
new file mode 100644
index 0000000..4fbbe1d
--- /dev/null
+++ 
b/pulsar-io/elastic-search/src/test/java/org/apache/pulsar/io/elasticsearch/IndexNameFormatterTest.java
@@ -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);
+    }
+}
diff --git a/site2/website-next/docs/io-elasticsearch-sink.md 
b/site2/website-next/docs/io-elasticsearch-sink.md
index b655917..af67daa 100644
--- a/site2/website-next/docs/io-elasticsearch-sink.md
+++ b/site2/website-next/docs/io-elasticsearch-sink.md
@@ -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.  |

Reply via email to