全文搜索存储过程运行缓慢,除非它快速运行

时间:2013-12-04 17:33:50

标签: sql sql-server stored-procedures full-text-search sql-execution-plan

我只是不明白。调用下面的存储过程的结果会在几秒或更短的时间内恢复。但是当@SearchPhrase参数发生变化时,需要几分钟才能完成。你可以看到我使用了WITH RECOMPILE选项。执行计划具有相同的百分比,无论是快速还是慢,所以我认为它不是索引问题

    CREATE PROCEDURE [dbo].[getItemsSearchKeyword] 
        @MaxItems int = 100,
        @LatestDate datetime = null,
        @ItemTypeIds tinyint = 255,
        @SearchPhrase nvarchar(256) = null,
        @EarliestDate datetime = null

    WITH RECOMPILE
    AS
    BEGIN
    SET NOCOUNT ON;

    --avoid parameter sniffing problems...
    DECLARE @MaxItemsC int = @MaxItems
    DECLARE @LatestDateC datetime = ISNULL(@LatestDate, GETUTCDATE())
    DECLARE @ItemTypeIdsC tinyint = @ItemTypeIds
    DECLARE @SearchPhraseC nvarchar(256) = @SearchPhrase
    DECLARE @EarliestDateC datetime = ISNULL(@EarliestDate, '1753-01-01')

    IF (@SearchPhraseC IS NULL OR LEN(@SearchPhraseC) = 0) RETURN

    -- these are used to filter the primary FTS index (4-bytes TimeTaken and 4-bytes Id make up the primary FTS key)
    DECLARE @EarlyDate bigint = CONVERT(bigint, @EarliestDateC, 112) * POWER(CAST(2 AS BIGINT), 32)
    DECLARE @LateDate  bigint = CONVERT(bigint, DATEADD(day, 1, @LatestDateC), 112) * POWER(CAST(2 AS BIGINT), 32) - 1

    SELECT
        TOP(@MaxItemsC)
        i.ID,
        i.TimeTaken,
        i.Title,
        i.[Description],
        i.BaseURL, 
        i.LargeURL,
        i.ThumbURL,
        i.imageWidth,
        i.imageHeight,
        i.ItemTypeId,
        i.StatusTypeId,
        i.Username

    FROM 
        Item i WITH (READPAST)

    WHERE 
        FREETEXT((i.Title,i.Tags), @SearchPhraseC) AND i.DateAndId BETWEEN @EarlyDate AND @LateDate
        AND i.TimeTaken > @EarliestDateC AND i.TimeTaken <= @LatestDateC
        AND ((@ItemTypeIdsC & i.ItemTypeId) != 0)
        AND i.StatusTypeId IN (1, 6, 7, 8, 9, 10)

    ORDER BY i.TimeTaken DESC

END

项目表很大 - 大约有4千万条记录。这是一个示例电话。第一次运行需要2分钟。后续运行在5秒或更短的范围内。但是当@SearchPhrase发生变化时,经常(但不总是)的时间可以追溯到几分钟才能完成。

getItemsSearchKeyword @ItemTypeIds = 255, @LatestDate = '2013-10-07 11:32:59 AM', @EarliestDate = '2013-10-06 11:42:59 AM', @MaxItems = 50, @SearchPhrase = 'upper';

有什么建议吗?感谢。

0 个答案:

没有答案