using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using Lucene.Net.Index;
6 using Lucene.Net.Store;
7 using Lucene.Net.Analysis.Standard;
8 using Lucene.Net.Documents;
9 using System.Data;
10 using System.Diagnostics;
11 using Lucene.Net.Search;
12
13 using Lucene.Net.QueryParsers;
14
15 namespace First
16 {
17 class Program
18 {
19 static string path = @"D:\Sample";
20
21 static void Main(string[] args)
22 {
23 //创建索引
24 CreateIndex();
25
26 var watch = Stopwatch.StartNew();
27
28 //搜索
29 IndexSearcher search = new IndexSearcher(path);
30
31 //查询表达式
32 QueryParser query = new QueryParser(string.Empty, new StandardAnalyzer());
33
34 //query.parse:注入查询条件
35 var hits = search.Search(query.Parse("Content:流行"));
36
37 for (int i = 0; i < hits.Length(); i++)
38 {
39 Console.WriteLine("当前内容:{0}", hits.Doc(i).Get("Content").Substring(0, 20) + "...");
40 }
41
42 watch.Stop();
43
44 Console.WriteLine("搜索耗费时间:{0}", watch.ElapsedMilliseconds);
45 }
46
47 static void CreateIndex()
48 {
49 //创建索引库目录
50 var directory = FSDirectory.GetDirectory(path, true);
51
52 //创建一个索引,采用StandardAnalyzer对句子进行分词
53 IndexWriter indexWriter = new IndexWriter(directory, new StandardAnalyzer());
54
55 var reader = DbHelperSQL.ExecuteReader("select * from News");
56
57 while (reader.Read())
58 {
59 //域的集合:文档,类似于表的行
60 Document doc = new Document();
61
62 //要索引的字段
63 doc.Add(new Field("ID", reader["ID"].ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
64 doc.Add(new Field("Title", reader["Title"].ToString(), Field.Store.NO, Field.Index.ANALYZED));
65 doc.Add(new Field("Content", reader["Content"].ToString(), Field.Store.YES, Field.Index.ANALYZED));
66
67 indexWriter.AddDocument(doc);
68 }
69
70 reader.Close();
71
72 //对索引文件进行优化
73 indexWriter.Optimize();
74
75 indexWriter.Close();
76 }
77 }
78 }
转载:http://www.cnblogs.com/huangxincheng/archive/2012/05/13/2497738.html