Skip to content

Instantly share code, notes, and snippets.

@jonsagara
Created December 20, 2011 17:31
Show Gist options
  • Save jonsagara/1502416 to your computer and use it in GitHub Desktop.
Save jonsagara/1502416 to your computer and use it in GitHub Desktop.
Bare bones Lucene.net console application
using System;
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;
namespace LuceneTest
{
class Program
{
/// <summary>
/// <para>
/// Updated version of Simone Chiaretta's tutorial code, which can be found here: http://codeclimber.net.nz/archive/2009/09/02/lucene.net-your-first-application.aspx.
/// </para>
/// <para>
/// This version works with Lucene.net 2.9.4.
/// </para>
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
//
// Initialize the Directory and the IndexWriter.
//
var dirInfo = new System.IO.DirectoryInfo("LuceneIndex");
Directory directory = FSDirectory.Open(dirInfo);
Analyzer analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29);
IndexWriter writer = new IndexWriter(directory, analyzer, IndexWriter.MaxFieldLength.LIMITED);
//
// Add Documents to the Index.
//
Document doc = new Document();
doc.Add(new Field("id", "1", Field.Store.YES, Field.Index.NO));
doc.Add(new Field("postBody", "lorem ipsum blah blah blah", Field.Store.YES, Field.Index.ANALYZED));
writer.AddDocument(doc);
writer.Optimize();
writer.Commit();
writer.Close();
//
// Create the Query.
//
QueryParser parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "postBody", analyzer);
Query query = parser.Parse("ipsum");
//
// Pass the Query to the IndexSearcher.
//
IndexSearcher searcher = new IndexSearcher(directory, readOnly: true);
TopDocs hits = searcher.Search(query, 200);
//
// Iterate over the Results.
//
int resultsCount = hits.ScoreDocs.Length;
Console.WriteLine("Found {0} results", resultsCount);
for(int ixResult = 0; ixResult < resultsCount; ixResult++)
{
var docResult = searcher.Doc(hits.ScoreDocs[ixResult].doc);
float score = hits.ScoreDocs[ixResult].score;
Console.WriteLine("Result num {0}, score {1}", ixResult + 1, score);
Console.WriteLine("ID: {0}", doc.Get("id"));
Console.WriteLine("Text found: {0}" + Environment.NewLine, doc.Get("postBody"));
}
Console.WriteLine("Press ENTER to quit...");
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment