Lucene.net Field contains mutiple values and who to search

混江龙づ霸主 提交于 2020-01-23 17:02:06

问题


Anyone know what the best way is to search on a Field that hold multiple values?

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

Let's say I want to search for all documents that has the tag "csharp", who could I best implement this?


回答1:


I think what you are looking for is adding multiple fields with the same name to a single Document.

What you do is create a single Document and add multiple tags Field to it.

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


来源:https://stackoverflow.com/questions/11128200/lucene-net-field-contains-mutiple-values-and-who-to-search

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!