Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/push_pr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ jobs:
compile_and_test:
strategy:
matrix:
flink: [ 2.2.1, 2.1.2 ]
flink: [ 2.2.1 ]
jdk: [ '11', '17, 21' ]
uses: apache/flink-connector-shared-utils/.github/workflows/ci.yml@ci_utils
with:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,21 @@
/*
* 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.flink.connector.elasticsearch.table;

import org.apache.flink.api.common.serialization.DeserializationSchema;
Expand All @@ -24,28 +42,28 @@
* from a logical description.
*/
public class ElasticsearchDynamicSource implements LookupTableSource, SupportsProjectionPushDown {
private final DecodingFormat<DeserializationSchema<RowData>> format;
private final ElasticsearchConfiguration config;
private final int lookupMaxRetryTimes;
private final LookupCache lookupCache;
private final String docType;
private final String summaryString;
private final ElasticsearchApiCallBridge<?> apiCallBridge;
private DataType physicalRowDataType;
protected final DecodingFormat<DeserializationSchema<RowData>> format;
protected final ElasticsearchConfiguration config;
protected final int maxRetryTimes;
protected final LookupCache lookupCache;
protected final String docType;
protected final String summaryString;
protected final ElasticsearchApiCallBridge<?> apiCallBridge;
protected DataType physicalRowDataType;

public ElasticsearchDynamicSource(
DecodingFormat<DeserializationSchema<RowData>> format,
ElasticsearchConfiguration config,
DataType physicalRowDataType,
int lookupMaxRetryTimes,
int maxRetryTimes,
String summaryString,
ElasticsearchApiCallBridge<?> apiCallBridge,
@Nullable LookupCache lookupCache,
@Nullable String docType) {
this.format = format;
this.config = config;
this.physicalRowDataType = physicalRowDataType;
this.lookupMaxRetryTimes = lookupMaxRetryTimes;
this.maxRetryTimes = maxRetryTimes;
this.summaryString = summaryString;
this.apiCallBridge = apiCallBridge;
this.lookupCache = lookupCache;
Expand All @@ -68,7 +86,7 @@ public LookupRuntimeProvider getLookupRuntimeProvider(LookupContext context) {
ElasticsearchRowDataLookupFunction<?> lookupFunction =
new ElasticsearchRowDataLookupFunction<>(
this.format.createRuntimeDecoder(context, physicalRowDataType),
lookupMaxRetryTimes,
maxRetryTimes,
config.getIndex(),
docType,
DataType.getFieldNames(physicalRowDataType).toArray(new String[0]),
Expand All @@ -84,7 +102,7 @@ public LookupRuntimeProvider getLookupRuntimeProvider(LookupContext context) {
}
}

private NetworkClientConfig buildNetworkClientConfig() {
protected NetworkClientConfig buildNetworkClientConfig() {
NetworkClientConfig.Builder builder = new NetworkClientConfig.Builder();
if (config.getUsername().isPresent()
&& !StringUtils.isNullOrWhitespaceOnly(config.getUsername().get())) {
Expand Down Expand Up @@ -123,7 +141,7 @@ public DynamicTableSource copy() {
format,
config,
physicalRowDataType,
lookupMaxRetryTimes,
maxRetryTimes,
summaryString,
apiCallBridge,
lookupCache,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ ElasticsearchConfiguration getConfiguration(FactoryUtil.TableFactoryHelper helpe
}

@Nullable
private LookupCache getLookupCache(ReadableConfig tableOptions) {
protected LookupCache getLookupCache(ReadableConfig tableOptions) {
LookupCache cache = null;
if (tableOptions
.get(LookupOptions.CACHE_TYPE)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
/*
* 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.flink.connector.elasticsearch.table.search;

import org.apache.flink.api.common.serialization.DeserializationSchema;
import org.apache.flink.table.data.GenericRowData;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.data.utils.JoinedRowData;
import org.apache.flink.table.functions.FunctionContext;
import org.apache.flink.table.functions.VectorSearchFunction;
import org.apache.flink.util.FlinkRuntimeException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

import static org.apache.flink.util.Preconditions.checkNotNull;

/**
* Base {@link VectorSearchFunction} implementation for Elasticsearch. Shared retry loop, result
* decoding and null-source filtering live here; version-specific subclasses only need to provide
* the client initialization and the search call.
*/
public abstract class AbstractElasticsearchVectorSearchFunction extends VectorSearchFunction {
private static final Logger LOG =
LoggerFactory.getLogger(AbstractElasticsearchVectorSearchFunction.class);
private static final long serialVersionUID = 1L;

protected final DeserializationSchema<RowData> deserializationSchema;
protected final String index;
protected final String searchColumn;
protected final String[] producedNames;
protected final int maxRetryTimes;

protected AbstractElasticsearchVectorSearchFunction(
DeserializationSchema<RowData> deserializationSchema,
int maxRetryTimes,
String index,
String searchColumn,
String[] producedNames) {
this.deserializationSchema =
checkNotNull(deserializationSchema, "No DeserializationSchema supplied.");
this.producedNames = checkNotNull(producedNames, "No fieldNames supplied.");
this.maxRetryTimes = maxRetryTimes;
this.index = index;
this.searchColumn = searchColumn;
}

@Override
public void open(FunctionContext context) throws Exception {
doOpen(context);
deserializationSchema.open(null);
}

@Override
public void close() throws Exception {
try {
doClose();
} finally {
super.close();
}
}

@Override
public Collection<RowData> vectorSearch(int topK, RowData features) throws IOException {
for (int retry = 0; retry <= maxRetryTimes; retry++) {
try {
SearchResult[] results = doSearch(topK, features);
if (results.length > 0) {
ArrayList<RowData> rows = new ArrayList<>(results.length);
for (SearchResult result : results) {
if (result.source == null) {
continue;
}
RowData row = parseSearchResult(result.source);
if (row == null) {
continue;
}
GenericRowData scoreData = new GenericRowData(1);
scoreData.setField(0, result.score);
rows.add(new JoinedRowData(row, scoreData));
}
rows.trimToSize();
return rows;
}
} catch (IOException e) {
LOG.error(String.format("Elasticsearch search error, retry times = %d", retry), e);
if (retry >= maxRetryTimes) {
throw new FlinkRuntimeException("Execution of Elasticsearch search failed.", e);
}
try {
Thread.sleep(1000L * retry);
} catch (InterruptedException e1) {
LOG.warn(
"Interrupted while waiting to retry failed elasticsearch search, aborting");
throw new FlinkRuntimeException(e1);
}
}
}
return Collections.emptyList();
}

/** Version-specific initialization (e.g., creating the underlying Elasticsearch client). */
protected abstract void doOpen(FunctionContext context) throws Exception;

/** Version-specific resource release (e.g., closing the underlying Elasticsearch client). */
protected abstract void doClose() throws Exception;

/** Execute a single vector search call and return raw results, excluding nothing. */
protected abstract SearchResult[] doSearch(int topK, RowData features) throws IOException;

private RowData parseSearchResult(String result) {
try {
return deserializationSchema.deserialize(result.getBytes());
} catch (IOException e) {
LOG.error("Deserialize search hit failed: " + e.getMessage());
return null;
}
}

/** One hit from Elasticsearch — raw JSON source plus score. */
protected static class SearchResult {
final String source;
final Double score;

public SearchResult(String source, Double score) {
this.source = source;
this.score = score;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* 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.flink.connector.elasticsearch.table.search;

/** Metric for vector search. */
public enum SearchMetric {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing Apache license header. Several other files have the same issue.

COSINE_SIMILARITY("cosineSimilarity"),
L1NORM("l1norm"),
L2NORM("l2norm"),
HAMMING("hamming"),
DOT_PRODUCT("dotProduct");

private final String name;

SearchMetric(String name) {
this.name = name;
}

@Override
public String toString() {
return name;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
* 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.flink.connector.elasticsearch.table.search;

import org.apache.flink.table.api.ValidationException;
import org.apache.flink.table.connector.source.VectorSearchTableSource;
import org.apache.flink.table.types.DataType;
import org.apache.flink.table.types.logical.ArrayType;
import org.apache.flink.table.types.logical.LogicalTypeRoot;
import org.apache.flink.table.types.logical.RowType;

/** Shared helpers for the Elasticsearch vector search table sources. */
public class VectorSearchUtils {

private VectorSearchUtils() {}

/**
* Validates the search columns declared on the given context and returns the resolved physical
* column name. Elasticsearch only supports a single, non-nested float-array column.
*/
public static String resolveSearchColumn(
DataType physicalRowDataType,
VectorSearchTableSource.VectorSearchContext vectorSearchContext) {
int[][] searchColumns = vectorSearchContext.getSearchColumns();

if (searchColumns.length != 1) {
throw new IllegalArgumentException(
String.format(
"Elasticsearch only supports one search columns now, but input search columns size is %d.",
searchColumns.length));
}
int[] searchColumn = searchColumns[0];
if (searchColumn.length != 1) {
throw new IllegalArgumentException(
"Elasticsearch doesn't support to search data using nested columns.");
}
int searchColumnIndex = searchColumn[0];

if (searchColumnIndex < 0
|| searchColumnIndex >= physicalRowDataType.getChildren().size()) {
throw new ValidationException(
String.format(
"The specified search column with index %d doesn't exist in schema.",
searchColumnIndex));
}

DataType searchColumnType = physicalRowDataType.getChildren().get(searchColumnIndex);
if (!searchColumnType.getLogicalType().is(LogicalTypeRoot.ARRAY)
|| !((ArrayType) searchColumnType.getLogicalType())
.getElementType()
.is(LogicalTypeRoot.FLOAT)) {
throw new UnsupportedOperationException(
String.format(
"Elasticsearch only supports search data using float vector now, but input search column type is %s.",
searchColumnType));
}

return ((RowType) physicalRowDataType.getLogicalType())
.getFieldNames()
.get(searchColumnIndex);
}
}
Loading
Loading