Entity Framework, Code First and Full Text Search

后端 未结 5 1083
逝去的感伤
逝去的感伤 2020-11-28 20:43

I realize that a lot of questions have been asked relating to full text search and Entity Framework, but I hope this question is a bit different.

I am using Entity F

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 21:16

    As the other guys mentioned, I would say start using Lucene.NET

    Lucene has a pretty high learning curve, but I found an wrapper for it called "SimpleLucene", that can be found on CodePlex

    Let me quote a couple of codeblocks from the blog to show you how easy it is to use. I've just started to use it, but got the hang of it really fast.

    First, get some entities from your repository, or in your case, use Entity Framework

    public class Repository
    {
        public IList Products {
            get {
                return new List {
                    new Product { Id = 1, Name = "Football" },
                    new Product { Id = 2, Name = "Coffee Cup"},
                    new Product { Id = 3, Name = "Nike Trainers"},
                    new Product { Id = 4, Name = "Apple iPod Nano"},
                    new Product { Id = 5, Name = "Asus eeePC"},
                };
            }
        }
    }
    

    The next thing you want to do is create an index-definition

    public class ProductIndexDefinition : IIndexDefinition {
        public Document Convert(Product p) {
            var document = new Document();
            document.Add(new Field("id", p.Id.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
            document.Add(new Field("name", p.Name, Field.Store.YES, Field.Index.ANALYZED));
            return document;
        }
    
        public Term GetIndex(Product p) {
            return new Term("id", p.Id.ToString());
        }
    }
    

    and create an search index for it.

    var writer = new DirectoryIndexWriter(
        new DirectoryInfo(@"c:\index"), true);
    
    var service = new IndexService();
    service.IndexEntities(writer, Repository().Products, ProductIndexDefinition());
    

    So, you now have an search-able index. The only remaining thing to do is.., searching! You can do pretty amazing things, but it can be as easy as this: (for greater examples see the blog or the documentation on codeplex)

    var searcher = new DirectoryIndexSearcher(
                    new DirectoryInfo(@"c:\index"), true);
    
    var query = new TermQuery(new Term("name", "Football"));
    
    var searchService = new SearchService();
    
    Func converter = (doc) => {
        return new ProductSearchResult {
            Id = int.Parse(doc.GetValues("id")[0]),
            Name = doc.GetValues("name")[0]
        };
    };
    
    IList results = searchService.SearchIndex(searcher, query, converter);
    

提交回复
热议问题