lucene是在JAVA中比较有名的开源项目,也有.NET移植版lucene.net,不过在apache的官方网站上还是一个孵化器项目,而且好像2007年就不更新了,现在codeplex上推出了LINQ To Lucene,真是一个好消息。
linq to lucene采用attribute的方式,非常简单方便。
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using Lucene.Linq.Mapping;
- using Lucene.Net.Analysis;
- using Lucene.Linq;
- namespace LinqToLucene1
- {
- [Document]
- public class Book : IIndexable, IHit
- {
- [Field(FieldIndex.Tokenized,FieldStore.Yes, IsDefault = true)]
- public string Title { get; set; }
- [Field(FieldIndex.Tokenized, FieldStore.Yes)]
- public string Author { get; set; }
- [Field(FieldIndex.Tokenized, FieldStore.Yes)]
- public string PubTime { get; set; }
- [Field(FieldIndex.Tokenized, FieldStore.Yes)]
- public string Publisher { get; set; }
- #region IHit Members
- public int DocumentId { get; set; }
- public float Relevance { get; set; }
- #endregion
- }
- }
然后就可以用linq的方式查询了,真是方便啊
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using Lucene.Net.Documents;
- using Lucene.Linq.Mapping;
- using Lucene.Linq;
- using Lucene.Net.Analysis;
- namespace LinqToLucene1
- {
- public class Program
- {
- static void Main(string[] args)
- {
- IIndex<Book> bookIndex = new Index<Book>();
- bookIndex.Add(new Book()
- {
- Title = "谁都逃不掉的金融危机",
- Author = "xxx",
- Publisher = "东方出版社",
- PubTime = "2008年12月"
- });
- bookIndex.Add(new Book()
- {
- Title = "许我向你看(“暖伤青春代言人” 辛夷坞《致我们终将逝去的青春》完美续作)",
- Author = "辛夷坞",
- Publisher = "河南文艺出版社",
- PubTime = "2008年12月"
- });
- bookIndex.Add(new Book()
- {
- Title = "大猫儿的TT奋斗史(都市小白领的爆雷囧事录)",
- Author = "阿巳",
- Publisher = "国际文化出版公司",
- PubTime = "2008年12月"
- });
- bookIndex.Add(new Book()
- {
- Title = "佳期如梦之海上繁花(匪我思存最新作品上市)",
- Author = "匪我思存",
- Publisher = "新世界出版社",
- PubTime = "2008年12月"
- });
- var result = from book in bookIndex
- where book.Author == "xxx"
- select book;
- foreach (Book book in result)
- {
- System.Console.WriteLine(book.Title);
- }
- System.Console.ReadLine();
- }
- }
- }
不过有个bug,如果写成from Book book in bookIndex 的话,就会报异常。
引用
一个未找到类型 “Lucene.Linq.Expressions.Query`1[[LinqToLucene1.Book, LinqToLucene1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]”上的构造函数。