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
3 changes: 2 additions & 1 deletion be/src/exprs/function/array/function_array_distance.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

#include <algorithm>

#include "exprs/function/function_inner_product.h"
#include "exprs/function/simple_function_factory.h"

namespace doris {
Expand Down Expand Up @@ -90,7 +91,7 @@ void register_function_array_distance(SimpleFunctionFactory& factory) {
factory.register_function<FunctionArrayDistance<L2Distance>>();
factory.register_function<FunctionArrayDistance<CosineDistance>>();
factory.register_function<FunctionArrayDistance<CosineSimilarity>>();
factory.register_function<FunctionArrayDistance<InnerProduct>>();
factory.register_function<FunctionInnerProduct>();
factory.register_function<FunctionArrayDistance<L2DistanceApproximate>>();
factory.register_function<FunctionArrayDistance<InnerProductApproximate>>();
}
Expand Down
479 changes: 479 additions & 0 deletions be/src/exprs/function/function_inner_product.h

Large diffs are not rendered by default.

429 changes: 429 additions & 0 deletions be/test/exprs/function/function_map_inner_product_test.cpp

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,17 @@
package org.apache.doris.nereids.trees.expressions.functions.scalar;

import org.apache.doris.catalog.FunctionSignature;
import org.apache.doris.nereids.exceptions.AnalysisException;
import org.apache.doris.nereids.trees.expressions.Expression;
import org.apache.doris.nereids.trees.expressions.functions.AlwaysNotNullable;
import org.apache.doris.nereids.trees.expressions.functions.ExplicitlyCastableSignature;
import org.apache.doris.nereids.trees.expressions.shape.BinaryExpression;
import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
import org.apache.doris.nereids.types.ArrayType;
import org.apache.doris.nereids.types.DataType;
import org.apache.doris.nereids.types.FloatType;
import org.apache.doris.nereids.types.MapType;
import org.apache.doris.nereids.types.coercion.AnyDataType;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
Expand All @@ -39,7 +43,10 @@ public class InnerProduct extends ScalarFunction implements ExplicitlyCastableSi

public static final List<FunctionSignature> SIGNATURES = ImmutableList.of(
FunctionSignature.ret(FloatType.INSTANCE)
.args(ArrayType.of(FloatType.INSTANCE), ArrayType.of(FloatType.INSTANCE))
.args(ArrayType.of(FloatType.INSTANCE), ArrayType.of(FloatType.INSTANCE)),
FunctionSignature.ret(FloatType.INSTANCE)
.args(MapType.of(new AnyDataType(0), FloatType.INSTANCE),
Comment thread
BiteTheDDDDt marked this conversation as resolved.
MapType.of(new AnyDataType(0), FloatType.INSTANCE))
);

/**
Expand All @@ -54,6 +61,39 @@ private InnerProduct(ScalarFunctionParams functionParams) {
super(functionParams);
}

@Override
public void checkLegalityBeforeTypeCoercion() {
checkMapKeyTypes(true);
}

@Override
public void checkLegalityAfterRewrite() {
checkMapKeyTypes(false);
}

private void checkMapKeyTypes(boolean allowNullKeyType) {
DataType firstKeyType = null;
for (Expression argument : getArguments()) {
DataType argumentType = argument.getDataType();
if (argumentType.isMapType()) {
DataType keyType = ((MapType) argumentType).getKeyType();
if (allowNullKeyType && keyType.isNullType()) {
continue;
}
if (!keyType.isIntegralType() && !keyType.isStringLikeType()) {
Comment thread
BiteTheDDDDt marked this conversation as resolved.
throw new AnalysisException("inner_product only supports integer or string map keys,"
+ " but got " + keyType.toSql() + " in expression " + toSql());
}
if (firstKeyType != null && firstKeyType.isIntegralType() != keyType.isIntegralType()) {
throw new AnalysisException("inner_product requires map keys from the same type family,"
+ " but got " + firstKeyType.toSql() + " and " + keyType.toSql()
+ " in expression " + toSql());
}
firstKeyType = keyType;
}
}
}

/**
* withChildren.
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
// 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.doris.nereids.trees.expressions.functions.scalar;

import org.apache.doris.nereids.exceptions.AnalysisException;
import org.apache.doris.nereids.parser.NereidsParser;
import org.apache.doris.nereids.rules.expression.ExpressionRewriteTestHelper;
import org.apache.doris.nereids.trees.expressions.Expression;
import org.apache.doris.nereids.types.IntegerType;
import org.apache.doris.nereids.types.MapType;
import org.apache.doris.qe.GlobalVariable;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class InnerProductTest {

private static final NereidsParser PARSER = new NereidsParser();

@Test
public void testInferNullMapKeyType() {
Expression expression = analyze(
"inner_product(map(null, cast(2 as float)),"
+ " map(cast(null as int), cast(3 as float)))");

Assertions.assertTrue(expression instanceof InnerProduct);
for (Expression argument : ((InnerProduct) expression).getArguments()) {
Assertions.assertTrue(argument.getDataType().isMapType());
Assertions.assertEquals(IntegerType.INSTANCE,
((MapType) argument.getDataType()).getKeyType());
}
Assertions.assertDoesNotThrow(expression::checkLegalityAfterRewrite);
}

@Test
public void testRejectMixedMapKeyFamiliesInBothCoercionModes() {
boolean originalBehavior = GlobalVariable.enableNewTypeCoercionBehavior;
try {
for (boolean enableNewBehavior : new boolean[] {true, false}) {
GlobalVariable.enableNewTypeCoercionBehavior = enableNewBehavior;
AnalysisException exception = Assertions.assertThrows(AnalysisException.class,
() -> analyze("inner_product(map(1, cast(2 as float)),"
+ " map('1', cast(3 as float)))"));
Assertions.assertTrue(exception.getMessage().contains("same type family"),
exception::getMessage);
}
} finally {
GlobalVariable.enableNewTypeCoercionBehavior = originalBehavior;
}
}

@Test
public void testRejectAllNullMapKeyTypesAfterCoercion() {
Expression expression = analyze(
"inner_product(map(null, cast(1 as float)),"
+ " map(null, cast(2 as float)))");

AnalysisException exception = Assertions.assertThrows(
AnalysisException.class, expression::checkLegalityAfterRewrite);
Assertions.assertTrue(exception.getMessage().contains(
"only supports integer or string map keys"), exception::getMessage);
}

private Expression analyze(String sql) {
return ExpressionRewriteTestHelper.typeCoercion(PARSER.parseExpression(sql));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
-- This file is automatically generated. You should know what you did if you want to edit this
-- !map_inner_product_rows --
1 10.0
2 -4.0
3 0.0

-- !map_inner_product_string_keys --
22.0

-- !map_inner_product_null_key --
38.0

-- !map_inner_product_inferred_null_key --
6.0

-- !map_inner_product_disjoint --
0.0

-- !map_inner_product_dense_compatibility --
11.0
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
// 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.

suite("test_map_inner_product", "p0,nonConcurrent") {
sql "drop table if exists test_map_inner_product"
sql """
create table test_map_inner_product (
id int,
lhs map<int, float>,
rhs map<int, float>
)
duplicate key(id)
distributed by hash(id) buckets 1
properties("replication_num" = "1")
"""
sql """
insert into test_map_inner_product values
(1, map(1, 1.0, 2, 2.0), map(2, 3.0, 1, 4.0)),
(2, map(1, -2.0, 3, 0.5), map(1, 4.0, 2, 99.0, 3, 8.0)),
(3, cast(map() as map<int, float>), map(1, 10.0)),
(4, map(1, cast(null as float)), map(1, 2.0)),
(5, cast(null as map<int, float>), map(1, 2.0))
"""

order_qt_map_inner_product_rows """
select id, inner_product(lhs, rhs)
from test_map_inner_product
where id <= 3
order by id
"""

qt_map_inner_product_string_keys """
select inner_product(
map('a', 2.0, 'b', 3.0),
map('b', 4.0, 'c', 100.0, 'a', 5.0))
"""

qt_map_inner_product_null_key """
select inner_product(
map(cast(null as int), 2.0, 1, 3.0),
map(1, 10.0, cast(null as int), 4.0))
"""

qt_map_inner_product_inferred_null_key """
select inner_product(
map(null, cast(2 as float)),
map(cast(null as int), cast(3 as float)))
"""

qt_map_inner_product_disjoint """
select inner_product(map(1, 2.0), map(2, 3.0))
"""

qt_map_inner_product_dense_compatibility """
select inner_product([1.0, 2.0], [3.0, 4.0])
"""

test {
sql """
select inner_product(lhs, rhs)
from test_map_inner_product
where id = 4
"""
exception "First argument for function inner_product cannot have null"
}

test {
sql """
select inner_product(lhs, rhs)
from test_map_inner_product
where id = 5
"""
exception "First argument for function inner_product cannot be null"
}

test {
sql """
select inner_product(
map(cast('2024-01-01' as date), cast(1 as float)),
map(cast('2024-01-01' as date), cast(2 as float)))
"""
exception "inner_product only supports integer or string map keys"
}

test {
sql """
select inner_product(
map(null, cast(1 as float)),
map(null, cast(2 as float)))
"""
exception "inner_product only supports integer or string map keys"
}

def originalTypeCoercionBehavior = sql """
show global variables like 'enable_new_type_coercion_behavior'
"""
try {
sql "set global enable_new_type_coercion_behavior = false"
test {
sql """
select inner_product(
map(1, cast(2 as float)),
map('1', cast(3 as float)))
"""
exception "inner_product requires map keys from the same type family"
}
} finally {
sql "set global enable_new_type_coercion_behavior = ${originalTypeCoercionBehavior[0][1]}"
}
}
Loading