1 sql-server snowflake-cloud-data-platform
假设我的表有一个字符串列,即VARCHAR()每个字符串都是一个句子。我想在此列中搜索某个词与另一个词相距很近的句子。
例如,如果我想在 SQL Server 中搜索在 'Smith' 的两个术语中包含 'John' 的句子,我会这样做
SELECT row_id
FROM my_table
WHERE CONTAINS(sentence_column, 'NEAR((John, Smith), 2)')
Run Code Online (Sandbox Code Playgroud)
这如何转化为雪花?
您可以编写一个 UDF 来近似该语法。这不是为了重现SQL Server的近似语法,而是展示了如何做到这一点。它只处理用于分词的空格,但可以修改以支持其他分词。它不区分大小写。如果您希望它区分大小写,您可以删除 toUpperCase() 方法。
create or replace function NEAR(STR string, STR1 string, STR2 string, DISTANCE float)
returns boolean
language javascript
as
$$
var firstWord = -1;
var secondWord = -1;
var words = STR.split(" ");
for (var i=0; i < words.length; i++){
if (words[i].toUpperCase() === STR1.toUpperCase()) firstWord = i;
if (words[i].toUpperCase() === STR2.toUpperCase()) secondWord = i;
}
return (firstWord >= 0) && (secondWord >= 0) && (secondWord - firstWord <= DISTANCE)
$$;
select near('John Jacob Smith', 'John', 'Smith', 2); --True
select near('John Jacob Williams Smith', 'John', 'Smith', 2); --False
Run Code Online (Sandbox Code Playgroud)