Linq的全文搜索

时间:2009-02-19 14:46:40

标签: linq linq-to-sql search full-text-search

在Linq中没有内置全文搜索,并且似乎没有很多关于这个主题的帖子所以我有一个游戏并为我的专业课提出了这个方法:

public static IEnumerable<TSource> GenericFullTextSearch<TSource>(string text, MyDataContext context)
{
    //Find LINQ Table attribute
    object[] info = typeof(TSource).GetCustomAttributes(typeof(System.Data.Linq.Mapping.TableAttribute), true);
    //Get table name
    String table = (info[0] as System.Data.Linq.Mapping.TableAttribute).Name;
    //Full text search on that table
    return context.ExecuteQuery<TSource>(String.Concat("SELECT * FROM ", table, " WHERE CONTAINS(*, {0})"), text);
}

并将此包装器添加到每个部分Linq类,其中有一个全文索引

public static IEnumerable<Pet> FullTextSearch(string text, MyDataContext context)
{
    return (LinqUtilities.GenericFullTextSearch<Pet>(text, context) as IEnumerable<Pet>);
}

所以现在我可以使用像

这样的简洁内容进行全文搜索
var Pets = Pet.FullTextSearch(helloimatextbox.Text, MyDataContext).Skip(10).Take(10);

我假设目前只需要进行非常基本的搜索。任何人都可以改进吗?是否可以实现作为扩展方法并避免使用包装器?

8 个答案:

答案 0 :(得分:6)

最新的解决方案是在sql中使用内联表值函数并将其添加到模型中

http://sqlblogcasts.com/blogs/simons/archive/2008/12/18/LINQ-to-SQL---Enabling-Fulltext-searching.aspx

答案 1 :(得分:3)

由于缺乏明确的示例,我感到非常沮丧...尤其是当存在潜在的大型数据集并且需要分页时。所以,这里有一个例子,希望包含你可能需要的一切: - )

create function TS_projectResourceSearch
    (   @KeyStr nvarchar(4000), 
        @OwnId int,
        @SkipN int,
        @TakeN int )
    returns @srch_rslt table (ProjectResourceId bigint not null, Ranking int not null )
    as 
    begin

        declare @TakeLast int
        set @TakeLast = @SkipN + @TakeN
        set @SkipN = @SkipN + 1

        insert into @srch_rslt  
        select pr.ProjectResourceId, Ranking
        from 
        (
            select t.[KEY] as ProjectResourceId, t.[RANK] as Ranking, ROW_NUMBER() over (order by t.[Rank] desc) row_num
            from containstable( ProjectResource,(ResourceInfo, ResourceName), @KeyStr )
            as t        
        ) as r
        join ProjectResource pr on r.ProjectResourceId = pr.ProjectResourceId
        where (pr.CreatorPersonId = @OwnId
            or pr.ResourceAvailType < 40)
            and r.row_num between @SkipN and @TakeLast
        order by r.Ranking desc 

        return
    end
    go


    select * from ts_projectResourceSearch(' "test*" ',1002, 0,1)

享受, 帕特里克

答案 2 :(得分:3)

我使用Provider Wrapper技术使用了一点hack。我有一个c#代码,可以在SQL中用FTS搜索MS SQL重写魔术字(你可以调整你喜欢的任何服务器)。

如果您有上下文类MyEntities,请创建类似

的子类
public class MyEntitiesWithWrappers : MyEntities
{
    private IEFTraceListener listener;
    public string FullTextPrefix = "-FTSPREFIX-";

    public MyEntitiesWithWrappers(): this("name=MyEntities")
    {
    }

    public MyEntitiesWithWrappers(string connectionString)
        : base(EntityConnectionWrapperUtils.CreateEntityConnectionWithWrappers(connectionString,"EFTracingProvider"))
    {
        TracingConnection.CommandExecuting += RewriteFullTextQuery;
    }

    /// <summary>
    /// Rewrites query that contains predefined prefix like: where n.NOTETEXT.Contains(Db.FullTextPrefix  + text) with SQL server FTS 
    /// To be removed when EF will support FTS
    /// </summary>
    /// <param name="o"></param>
    /// <param name="args"></param>
    public void RewriteFullTextQuery(object o, CommandExecutionEventArgs args)
    {
        var text = args.Command.CommandText;
        for (int i = 0; i < args.Command.Parameters.Count; i++)
        {
            DbParameter parameter = args.Command.Parameters[i];
            if (parameter.DbType.In(DbType.String, DbType.AnsiString, DbType.StringFixedLength, DbType.AnsiStringFixedLength))
            {
                if (parameter.Value == DBNull.Value)
                    continue;
                var value = (string) parameter.Value;
                parameter.Size = 4096;
                if (value.IndexOf(FullTextPrefix) >= 0)
                {
                    value = value.Replace(FullTextPrefix, ""); // remove prefix we added n linq query
                    value = value.Substring(1, value.Length-2); // remove %% escaping by linq translator from string.Contains to sql LIKE
                    parameter.Value = value;
                    args.Command.CommandText = Regex.Replace(text,
                        string.Format(@"\(\[(\w*)\].\[(\w*)\]\s*LIKE\s*@{0}\s?(?:ESCAPE '~')\)", parameter.ParameterName), 
                        string.Format(@"contains([$1].[$2], @{0})", parameter.ParameterName));
                }
            }
        }
    }

  }

然后像这样使用它:

var fullTextSearch = Db.FullTextPrefix + textToSearch;
var q = Db.Notes.Where(n => !n.Private && n.NoteText.Contains(fullTextSearch));

答案 3 :(得分:2)

使用CONTAINSTABLE

稍微好一点的方法(使得排名生效)
String pkey = context.Mapping.GetTable(typeof(TSource)).RowType.DataMembers.SingleOrDefault(x => x.IsPrimaryKey).Name;
string query = String.Concat(@"SELECT *
    FROM ", table, @" AS FT_TBL INNER JOIN
    CONTAINSTABLE(", table, @", *, {0}) AS KEY_TBL
    ON FT_TBL.", pkey, @" = KEY_TBL.[KEY]
    ORDER BY KEY_TBL.[RANK] DESC");
return context.ExecuteQuery<TSource>(query, text);

答案 4 :(得分:1)

.NET Core 2.1 及更高版本支持允许使用 FREETEXTFREETEXTTABLE 搜索的扩展方法

using Microsoft.EntityFrameworkCore;

var results = dbContext.MyTable
        .Where(e => EF.Functions.FreeText("*", "search criteria"));

FreeText 函数在 Microsoft.EntityFrameworkCore.SqlServer 中定义,因此您的项目必须引用该包。

Documentation

答案 5 :(得分:0)

我一直在努力解决确切的问题。我喜欢在我的LINQtoSQL中编写SQL逻辑,但我需要一种方法来进行全文搜索。现在我只是使用SQL函数,然后调用内联linq查询的用户定义函数。不确定这是否是最有效的方式。你觉得怎么样?

答案 6 :(得分:-3)

你可以做这样的事情

    var results = (from tags in _dataContext.View_GetDeterminationTags
                   where tags.TagName.Contains(TagName) ||
                   SqlMethods.Like(tags.TagName,TagName)
                   select new DeterminationTags
                   {
                       Row = tags.Row,
                       Record = tags.Record,
                       TagID = tags.TagID,
                       TagName = tags.TagName,
                       DateTagged = tags.DateTagged,
                       DeterminationID = tags.DeterminationID,
                       DeterminationMemberID = tags.DeterminationMemberID,
                       MemberID = tags.MemberID,
                       TotalTagged = tags.TotalTagged.Value
                   }).ToList();

注意TagName.Contains还在哪里SQLMethods.Like只是使用

using System.Data.Linq.SqlClient;

获取对SQLMethods的访问权。

答案 7 :(得分:-4)

dswatik - 想要全文搜索的原因是.contains转换为

SELECT * FROM MYTABLE WHERE COLUMNNAME LIKE '%TEXT%'

这会忽略任何索引,并且在大桌子上很糟糕。