110,536
社区成员
发帖
与我相关
我的任务
分享
public string CreatLC()
{
try
{
string sql = "SELECT * FROM Product";
List<Product> a = new List<Product>();
CreatLucene<Product>.PrepareIndex(new PanGuAnalyzer(), true, Config.INDEX_Product, a, sql);
return "成功";
}
catch (Exception)
{
return "失败";
}
}
public static void PrepareIndex(Analyzer analyzer, bool b, string path, List<T> list, string sql)
{
//根据地址创建目录
DirectoryInfo dirInfo = Directory.CreateDirectory(path);
//FSDirectory:指定索引库文件存放位置,是Diectory的子类
//将索引文件存放在创建的目录dirInfo中
LuceneIO.Directory directory = LuceneIO.FSDirectory.Open(dirInfo);
//IndexWriter:对索引文件进行写的类
IndexWriter writer = new IndexWriter(directory, analyzer, b, IndexWriter.MaxFieldLength.LIMITED);
DBHelper db = DBHelper.GetInstance();
list = db.Fetch<T>(sql);
Type type = typeof(T);
PropertyInfo[] ps = type.GetProperties();
foreach (var item in list)
{
CreateIndex(writer, item);
}
writer.Optimize();
writer.Close();
}
/// <summary>
/// 创建索引
/// </summary>
/// <param name="analyzer"></param>
/// <param name="title"></param>
/// <param name="content"></param>
private static void CreateIndex(IndexWriter writer, T entity)
{
try
{
Document doc = new Document();
Type type = typeof(T);
PropertyInfo[] ps = type.GetProperties();
foreach (PropertyInfo p in ps)
{
object value = p.GetValue(entity, null);
if (value != null)
{
//if (p.Name == "pinyin")
//{
// doc.Add(new Field(p.Name, value.ToString(), Field.Store.YES, Field.Index.ANALYZED));//存储且索引
//}
//else
//{
doc.Add(new Field(p.Name, value.ToString(), Field.Store.YES, Field.Index.ANALYZED));//存储且索引
//}
}
}
writer.AddDocument(doc);
}
catch (FileNotFoundException fnfe)
{
throw fnfe;
}
catch (Exception ex)
{
throw ex;
}
}