2012-06-20 71 views
0

任何人都知道什麼最好的方法是在一個字段上搜索多個值?Lucene.net字段包含多個值和搜索對象

string tagString = ""; 
foreach(var tag in tags) 
{ 
    tagString = tagString += ":" + tag; 
} 
doc.Field(new Field("Tags", tagString, Field.Store.YES, Field.Index.Analyzed); 

比方說,我想搜索所有具有標籤「csharp」的文檔,誰能最好地實現它?

回答

4

我認爲你要找的是將多個同名的字段添加到一個Document

你要做的是創建一個Document併爲其添加多個標籤Field

RAMDirectory ramDir = new RAMDirectory(); 

IndexWriter writer = new IndexWriter(ramDir, new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29)); 


Document doc = new Document(); 
Field tags = null; 

string [] articleTags = new string[] {"C#", "WPF", "Lucene" }; 
foreach (string tag in articleTags) 
{ 
    // adds a field with same name multiple times to the same document 
    tags = new Field("tags", tag, Field.Store.YES, Field.Index.NOT_ANALYZED); 
    doc.Add(tags); 
} 

writer.AddDocument(doc); 
writer.Commit(); 

// search 
IndexReader reader = writer.GetReader(); 
IndexSearcher searcher = new IndexSearcher(reader); 

// use an analyzer that treats the tags field as a Keyword (Not Analyzed) 
PerFieldAnalyzerWrapper aw = new PerFieldAnalyzerWrapper(new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29)); 
aw.AddAnalyzer("tags", new KeywordAnalyzer()); 

QueryParser qp = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "tags", aw); 

Query q = qp.Parse("+WPF +Lucene"); 
TopDocs docs = searcher.Search(q, null, 100); 
Console.WriteLine(docs.totalHits); // 1 hit 

q = qp.Parse("+WCF +Lucene"); 
docs = searcher.Search(q, null, 100); 
Console.WriteLine(docs.totalHits); // 0 hit 
+0

Tnx爲您的回覆,我似乎只是做我想要的!但如何用一個額外的標籤更新現有的文檔? Cheerz – Martijn

+0

在lucene中,您永遠不會「更新」文檔,您將其刪除,然後將其重新添加到索引中。 IndexWriter有一個UpdateDocument()方法,它只是一個簡便的方法,它刪除並重新將文檔添加到索引。 –