LINQ To Lucene简单介绍

本文向大家介绍LINQ To Lucene,可能好多人还不了解LINQ To Lucene,没有关系,看完本文你肯定有不少收获,希望本文能教会你更多东西。

lucene是在JAVA中比较有名的开源项目,也有.NET移植版lucene.net,不过在apache的官方网站上还是一个孵化器项目,而且好像2007年就不更新了,现在codeplex上推出了LINQ To Lucene,真是一个好消息。

 
 
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using Lucene.Linq.Mapping;  
  6. using Lucene.Net.Analysis;  
  7. using Lucene.Linq;  
  8.  
  9. namespace LinqToLucene1  
  10. {  
  11. [Document]  
  12. public class Book : IIndexable, IHit  
  13. {  
  14. [Field(FieldIndex.Tokenized,FieldStore.Yes, IsDefault = true)]  
  15. public string Title { get; set; }  
  16.  
  17. [Field(FieldIndex.Tokenized, FieldStore.Yes)]  
  18. public string Author { get; set; }  
  19.  
  20. [Field(FieldIndex.Tokenized, FieldStore.Yes)]  
  21. public string PubTime { get; set; }  
  22.  
  23. [Field(FieldIndex.Tokenized, FieldStore.Yes)]  
  24. public string Publisher { get; set; }  
  25.  
  26. region IHit Members  
  27.  
  28. public int DocumentId { get; set; }  
  29.  
  30. public float Relevance { get; set; }  
  31.  
  32. endregion  
  33. }  

linq to lucene采用attribute的方式,非常简单方便。

 
 
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using Lucene.Net.Documents;  
  6. using Lucene.Linq.Mapping;  
  7. using Lucene.Linq;  
  8. using Lucene.Net.Analysis;  
  9.  
  10. namespace LinqToLucene1  
  11. {  
  12. public class Program  
  13. {  
  14. static void Main(string[] args)  
  15. {  
  16. IIndex<Book> bookIndex = new Index<Book>();  
  17. bookIndex.Add(new Book()  
  18. {  
  19. Title = "谁都逃不掉的金融危机",  
  20. Author = "xxx",  
  21. Publisher = "东方出版社",  
  22. PubTime = "2008年12月" 
  23. });  
  24. bookIndex.Add(new Book()  
  25. {  
  26. Title = "许我向你看(“暖伤青春代言人” 辛夷坞《致我们终将逝去的青春》***续作)",  
  27. Author = "辛夷坞",  
  28. Publisher = "河南文艺出版社",  
  29. PubTime = "2008年12月" 
  30. });  
  31. bookIndex.Add(new Book()  
  32. {  
  33. Title = "大猫儿的TT奋斗史(都市小白领的爆雷囧事录)",  
  34. Author = "阿巳",  
  35. Publisher = "国际文化出版公司",  
  36. PubTime = "2008年12月" 
  37. });  
  38. bookIndex.Add(new Book()  
  39. {  
  40. Title = "佳期如梦之海上繁花(匪我思存***作品上市)",  
  41. Author = "匪我思存",  
  42. Publisher = "新世界出版社",  
  43. PubTime = "2008年12月" 
  44. });  
  45.  
  46. var result = from book in bookIndex  
  47. where book.Author == "xxx"  
  48. select book;  
  49.  
  50. foreach (Book book in result)  
  51. {  
  52. System.Console.WriteLine(book.Title);  
  53. }  
  54.  
  55. System.Console.ReadLine();  
  56. }  
  57. }  

不过有个bug,如果写成from Book book in bookIndex 的话,就会报异常。

【编辑推荐】

  1. Linq结果集形状概述
  2. Linq存储过程返回详解
  3. Linq调用LoadProducts方法
  4. Linq使用数据表简单描述
  5. Linq对象引用简单介绍
THE END