SQL Server Full-Text Search for exact match with fallback

后端 未结 4 795
滥情空心
滥情空心 2021-01-11 12:29

First off there seems to be no way to get an exact match using a full-text search. This seems to be a highly discussed issue when using the full-text search method and there

4条回答
  •  说谎
    说谎 (楼主)
    2021-01-11 12:36

    You should use full text search CONTAINSTABLE to find the top 100 (possibly 200) candidate results and then order the results you found using your own criteria.

    It sounds like you'd like to ORDER BY

    1. exact match of the phrase (=)
    2. the fully matched phrase (LIKE)
    3. higher value for the Popularity column
    4. the Rank from the CONTAINSTABLE

    But you can toy around with the exact order you prefer.

    In SQL that looks something like:

    DECLARE @title varchar(255)
    SET @title = '"Toy Story"'
    --need to remove quotes from parameter for LIKE search
    DECLARE @title2 varchar(255)
    SET @title2 = REPLACE(@title, '"', '')
    
    SELECT
        m.ID,
        m.title,
        m.Popularity,
        k.Rank
    FROM Movies m
    INNER JOIN CONTAINSTABLE(Movies, title, @title, 100) as [k]
        ON m.ID = k.[Key]
    ORDER BY 
      CASE WHEN m.title = @title2 THEN 0 ELSE 1 END,
      CASE WHEN m.title LIKE @title2 THEN 0 ELSE 1 END,
      m.popularity desc,
      k.rank
    

    See SQLFiddle

提交回复
热议问题