|
以下例子采用 Lucene.NET 1.9 版本,可取去 Lucene.NET 下载。
1. 基本应用
using System;
using System.Collections.Generic;
using System.Text;
using Lucene.NET;
using Lucene.NET.Analysis;
using Lucene.NET.Analysis.Standard;
using Lucene.NET.Documents;
using Lucene.NET.Index;
using Lucene.NET.QueryParsers;
using Lucene.NET.Search;
using Lucene.NET.Store;
using Lucene.NET.Util;
namespace ConsoleApplication1.Lucene
{
public class LuceNETest
{
private const string FieldName = "name";
private const string FieldValue = "value";
private Directory directory = new RAMDirectory();
private Analyzer analyzer = new StandardAnalyzer();
public LuceNETest()
{
}
private void Index()
{
IndexWriter writer = new IndexWriter(directory, analyzer, true);
writer.maxFieldLength = 1000;
for (int i = 1; i <= 100; i++)
{
Document document = new Document();
document.Add(new Field(FieldName, "name" + i, Field.Store.YES, Field.Index.UN_TOKENIZED));
document.Add(new Field(FieldValue, "Hello, World!", Field.Store.YES, Field.Index.TOKENIZED));
writer.AddDocument(document);
}
writer.Optimize();
writer.Close();
}
private void Search()
{
Query query = QueryParser.Parse("name*", FieldName, analyzer);
IndexSearcher searcher = new IndexSearcher(directory);
Hits hits = searcher.Search(query);
Console.WriteLine("符合条件记录:{0}; 索引库记录总数:{1}", hits.Length(), searcher.Reader.NumDocs());
for (int i = 0; i < hits.Length(); i++)
{
int docId = hits.Id(i);
string name = hits.Doc(i).Get(FieldName);
string value = hits.Doc(i).Get(FieldValue);
float score = hits.Score(i);
Console.WriteLine("{0}: DocId:{1}; Name:{2}; Value:{3}; Score:{4}",
i + 1, docId, name, value, score);
}
searcher.Close();
}
}
}
NET技术:Lucene.Net操作上的一些技巧,转载需保留来源!
郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。