linq - Linq 中的全文搜索

标签 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);

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

最佳答案

最简洁的解决方案是在 sql 中使用内联表值函数并将其添加到您的模型中
http://sqlblogcasts.com/blogs/simons/archive/2008/12/18/LINQ-to-SQL---Enabling-Fulltext-searching.aspx

To get it working you need to create a table valued function that does nothing more than a CONTAINSTABLE query based on the keywords you pass in,

create function udf_sessionSearch
      (@keywords nvarchar(4000)) returns table as   return (select [SessionId],[rank]
            from containstable(Session,(description,title),@keywords))

You then add this function to your LINQ 2 SQL model and he presto you can now write queries like.

var sessList = from s   in DB.Sessions
               join fts in DB.udf_sessionSearch(SearchText) on s.sessionId equals fts.SessionId
               select s;

关于linq - Linq 中的全文搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/565617/

相关文章:

linq-to-sql - LINQ + 类型表最佳实践

algorithm - 检索包含指定点的矩形集

算法优化——多点之间的最短路线

c# - 将 List<T> 转换为 HashTable

c# - 多个 LINQ 表达式和动态属性

c# - linq to sql SubmitChanges 不触发具有多个 InsertOnSubmit 或 DeleteOnSubmit 的触发器

search - SOLR中无法按范围删除

c# - Linq 查询适用于 null 但不适用于 int?在 where 子句中

c# - 使用 C# 使用 LINQ 交换 List<> 元素

c# - LINQ to SQL (NHibernate) : OrderBy vs OrderByDescending abstraction