代码之家  ›  专栏  ›  技术社区  ›  Armstrongest

如何使关键字顺序在搜索中更具相关性?

  •  2
  • Armstrongest  · 技术社区  · 15 年前

    在我的数据库中,我有一个 关键词 存储以逗号分隔的关键字列表的字段。

    例如,史莱克娃娃可能有以下关键字:

    ogre, green, plush, hero, boys' toys
    

    一个“豆豆宝宝”娃娃 食人魔 可能有:

    beanie baby, kids toys, beanbag toys, soft, infant, ogre
    

    (这完全是人为的例子。)

    我想做的是,如果消费者搜索“食人魔”,我希望“史莱克”娃娃在搜索结果中出现得更高。

    我的内容管理员认为,如果关键字在列表中的前面,它应该得到更高的排名。(这对我来说是有意义的,这使得我很容易让他们控制搜索结果的相关性)。

    下面是一个简化的查询:

    SELECT
    p.ProductID         AS ContentID
    , p.ProductName     AS Title
    , p.ProductCode     AS Subtitle
    , 100               AS Rank
    , p.ProductKeywords AS Keywords
    FROM Products AS p
    WHERE FREETEXT( p.ProductKeywords, @SearchPredicate )
    

    我在考虑用以下方式取代军衔:

    , 200 - INDEXOF(@SearchTerm)            AS Rank
    

    这个“应该”根据关键字结果的相关性对其进行排名

    我知道indexof不是SQL命令…但这是我想要完成的事情。

    我走这条路对吗?

    可以这样做吗?

    这有道理吗?

    2 回复  |  直到 15 年前
        1
  •  1
  •   Philip Kelley    15 年前

    根据您所拥有的和不需要修改现有结构,这很好地说明了跛脚的SQL Server是如何进行字符串操作的,但它是可以工作的。逻辑分析:

    DECLARE
      @ProductKeywords varchar(100)
     ,@SearchPredicate varchar(10)
    
    SET @ProductKeywords = 'The,quick,brown,fox,jumps,over'
    SET @SearchPredicate= 'fox'
    
    --  Where in the string your search value is
    print charindex(@SearchPredicate, @ProductKeywords)
    
    --  The string up through but not including your search string
    print left(@ProductKeywords, charindex(@SearchPredicate, @ProductKeywords))
    
    --  Remove the commas (your delimiter) from the above
    print replace(left(@ProductKeywords, charindex(@SearchPredicate, @ProductKeywords)), ',', '')
    
    --  This is how many characters are left
    print len(replace(left(@ProductKeywords, charindex(@SearchPredicate, @ProductKeywords)), ',', ''))
    
    --  This is how many delimiters you removed,
    --  = the number of words (minus one) from the "first" the found word was,
    --  = a weighting factor you can use
    print charindex(@SearchPredicate, @ProductKeywords) - len(replace(left(@ProductKeywords, charindex(@SearchPredicate, @ProductKeywords)), ',', ''))
    

    将@productkeyword替换为p.productkeywords,这样就可以了。(请注意,我对全文查询引擎没有任何经验。它可能会或可能不会影响此代码。)

        2
  •  1
  •   John    15 年前

    我能建议另一种方法吗?

    如果有一个链接表productkeywords:

    ID_ProductKeyword(pk)
    ProductID(int)
    KeywordID(int)
    Weight(int)
    

    这表示了上述关系:关键字和产品之间的关系,以及特定关键字对特定产品的重要性(权重越高,索引越高)。

    另一个好处是,您可以根据关键字为用户提供正确产品的频率动态更新权重。或者,如果您发现遗漏了关键字关联,您可以轻松添加关键字关联(他们是否搜索 梅尔斯 记得史莱克是个怪物吗?)

    我的两分钱。