全文搜索 MS SQL

Full text search for MS SQL

我有一个存储用户输入的搜索条件的数据库,我想分析某些词的使用频率。 "problem" 是许多搜索具有相似的含义,但伴随着一个或多个单词。示例(在此示例中 "foo" 是有趣的词):

bar
foo 2015
show me foo
germany foo

我想确定foo被使用了3次。我需要以编程方式执行此操作,这意味着使用 SQL 命令将是理想的解决方案。使用的词因用户行为而异。因此,我事先不知道使用了哪些词,我需要逻辑自行确定。

在此 This Answer 上进行扩展(函数归功于 Aaron Bertrand),您可以通过创建拆分函数并使用 Cross ApplyGroup By 来实现:

CREATE FUNCTION dbo.SplitStrings
(
    @List       NVARCHAR(MAX),
    @Delimiter  NVARCHAR(255)
)
RETURNS TABLE
AS
    RETURN (SELECT Number = ROW_NUMBER() OVER (ORDER BY Number),
        Item FROM (SELECT Number, Item = LTRIM(RTRIM(SUBSTRING(@List, Number, 
        CHARINDEX(@Delimiter, @List + @Delimiter, Number) - Number)))
    FROM (SELECT ROW_NUMBER() OVER (ORDER BY s1.[object_id])
        FROM sys.all_objects AS s1 CROSS APPLY sys.all_objects) AS n(Number)
    WHERE Number <= CONVERT(INT, LEN(@List))
        AND SUBSTRING(@Delimiter + @List, Number, 1) = @Delimiter
    ) AS y);
GO 

示例数据:

Create Table SplitTest
(
    A   Varchar (100)
)

Insert  SplitTest
Values  ('bar'), 
        ('foo 2015'), 
        ('show me foo'), 
        ('germany foo')

查询:

Select      f.Item, Count(*) Count
From        SplitTest                   As s
Cross Apply dbo.SplitStrings(s.A, ' ')  As F
Group By    F.Item
Order By    Count Desc

结果:

Item    Count
foo     3
germany 1
me      1
show    1
2015    1
bar     1

我认为这是使用 sql 服务器的全文搜索功能的一个想法问题。全文搜索就是解决这个问题的。

https://msdn.microsoft.com/en-us/library/ms142571.aspx

引用该页面:

Full-Text Search Queries

After columns have been added to a full-text index, users and applications can run full-text queries on the text in the columns. These queries can search for any of the following:

  • One or more specific words or phrases (simple term)

  • A word or a phrase where the words begin with specified text (prefix term)

  • Inflectional forms of a specific word (generation term)

  • A word or phrase close to another word or phrase (proximity term)

  • Synonymous forms of a specific word (thesaurus)

  • Words or phrases using weighted values (weighted term)

当产品中已经存在该功能时,为什么还要重新发明?

您应该阅读有关文本挖掘的内容。首先,您应该获取停用词列表 http://en.wikipedia.org/wiki/Stop_words 并加载到您的 sql 服务器,然后您需要将所有短语拆分为 ngram - 在您的情况下它将是 1gram,这意味着单个单词,比你需要检查这些词是否在停用词列表中,如果不在计数。 我很确定您会在网上找到一些教程,但我认为这不适合 sql 服务器 - 我建议使用自定义工具或至少使用自定义 coponent\scripts 的 ssis。这会更容易。正如有人建议的那样,您也可以为全文搜索提供机会,但这取决于您是否可以打开它并使用它。