-
-
Save sjkp/995ae869d3c57216f950d74e289c59e5 to your computer and use it in GitHub Desktop.
Quick and complete Lucene.Net example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Globalization; | |
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 Version = Lucene.Net.Util.Version; | |
namespace ConsoleApplication1 | |
{ | |
class Program | |
{ | |
static void Main() | |
{ | |
var dir = new RAMDirectory(); | |
var analyzer = new StandardAnalyzer(Version.LUCENE_30); | |
// Index | |
using (var writer = new IndexWriter(dir, analyzer, IndexWriter.MaxFieldLength.UNLIMITED)) | |
{ | |
int i = 1; | |
foreach (var line in new[] | |
{ | |
"Take this kiss upon the brow!", | |
"And, in parting from you now,", | |
"Thus much let me avow--", | |
"You are not wrong, who deem", | |
"That my days have been a dream;" | |
}) | |
{ | |
var bodyField = new Field("line", line, Field.Store.YES, Field.Index.ANALYZED); | |
var idField = new Field("number", (i++).ToString(CultureInfo.InvariantCulture), Field.Store.YES, Field.Index.NOT_ANALYZED); | |
var document = new Document(); | |
document.Add(bodyField); | |
document.Add(idField); | |
writer.AddDocument(document); | |
} | |
writer.Optimize(); | |
} | |
// Search | |
using (var indexSearcher = new IndexSearcher(dir)) | |
{ | |
var queryParser = new QueryParser(Version.LUCENE_30, "line", analyzer); | |
foreach (var term in new[] { "days", "much wrong", "kiss" }) | |
{ | |
Console.WriteLine("__________________________________________________________"); | |
Console.WriteLine("Searching for the term \"{0}\"...", term); | |
Query query = queryParser.Parse(term); | |
TopDocs hits = indexSearcher.Search(query, 10); | |
foreach (ScoreDoc scoreDoc in hits.ScoreDocs) | |
{ | |
Document document = indexSearcher.Doc(scoreDoc.Doc); | |
Console.WriteLine("{0} {1} {2}", scoreDoc.Score, document.Get("number"), document.Get("line")); | |
} | |
} | |
} | |
Console.ReadLine(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment