How do I assign weights to different columns in a full text search?

前端 未结 1 1533
挽巷
挽巷 2021-01-04 22:10

In my full text search query, I want to assign particular columns a higher weightage. Consider this query:

SELECT Key_Table.RANK, FT_Table.* FROM Restaurants         


        
1条回答
  •  再見小時候
    2021-01-04 22:46

    The best solution is to use ContainsTable. Use a union to create a query that searches all 3 columns and adds an integer used to indicate which column was searched. Sort the results by that integer and then rank desc.

    The rank is internal to sql server and not something you can adjust.

    You could also manipulate the returned rank by dividing the rank by the integer (Name would be divided by 1, Keyword and Location by 2 or higher). That would cause the appearance of different rankings.

    Here's some example sql
    : --Recommend using start change tracking and start background updateindex (see books online)

        SELECT 1 AS ColumnLocation, Key_Table.Rank, FT_Table.* FROM Restaurants AS FT_Table
     INNER JOIN ContainsTable(Restaurant, Name, 'chilly chicken') AS Key_Table ON 
    FT_Table.RestaurantId = Key_Table.[Key]
    
    UNION SELECT 2 AS ColumnLocation, Key_Table.Rank, FT_Table.* FROM Restaurants AS FT_Table
     INNER JOIN ContainsTable(Restaurant, Keywords, 'chilly chicken') AS Key_Table ON 
    FT_Table.RestaurantId = Key_Table.[Key]
    
    UNION SELECT 3 AS ColumnLocation, Key_Table.Rank, FT_Table.* FROM Restaurants AS FT_Table
     INNER JOIN ContainsTable(Restaurant, Location, 'chilly chicken') AS Key_Table ON 
    FT_Table.RestaurantId = Key_Table.[Key]
    
    ORDER BY ColumnLocation, Rank DESC
    

    In a production environment, I would insert the output of the query into a table variable to perform any additional manipulation before returning the results (may not be necessary in this case). Also, avoid using *, just list the columns you really need.

    Edit: You're right about using ContainsTable, you would have to modify the keywords to be '"chilly*" AND "chicken*"', I do this using a process that tokenizes an input phrase. If you don't want to do that, just replace every instance of ContainsTable above with FreeTextTable, the query will still work the same.

    0 讨论(0)
提交回复
热议问题