Fork me on GitHub

Lucene.NET is a high performance search library for .NET

dotnet add package Lucene.Net --prerelease

Create an index and define a text analyzer


// Ensures index backward compatibility
const LuceneVersion AppLuceneVersion = LuceneVersion.LUCENE_48;

// Construct a machine-independent path for the index
var basePath = Environment.GetFolderPath(
    Environment.SpecialFolder.CommonApplicationData);
var indexPath = Path.Combine(basePath, "index");

using var dir = FSDirectory.Open(indexPath);

// Create an analyzer to process the text
var analyzer = new StandardAnalyzer(AppLuceneVersion);

// Create an index writer
var indexConfig = new IndexWriterConfig(AppLuceneVersion, analyzer);
using var writer = new IndexWriter(dir, indexConfig);

Add to the index

var source = new
{
    Name = "Kermit the Frog",
    FavoritePhrase = "The quick brown fox jumps over the lazy dog"
};
var doc = new Document
{
    // StringField indexes but doesn't tokenize
    new StringField("name", 
        source.Name, 
        Field.Store.YES),
    new TextField("favoritePhrase", 
        source.FavoritePhrase, 
        Field.Store.YES)
};

writer.AddDocument(doc);
writer.Flush(triggerMerge: false, applyAllDeletes: false);

Construct a query

// Search with a phrase
var phrase = new MultiPhraseQuery
{
    new Term("favoritePhrase", "brown"),
    new Term("favoritePhrase", "fox")
};

Fetch the results

// Re-use the writer to get real-time updates
using var reader = writer.GetReader(applyAllDeletes: true);
var searcher = new IndexSearcher(reader);
var hits = searcher.Search(phrase, 20 /* top 20 */).ScoreDocs;

// Display the output in a table
Console.WriteLine($"{"Score",10}" +
    $" {"Name",-15}" +
    $" {"Favorite Phrase",-40}");
foreach (var hit in hits)
{
    var foundDoc = searcher.Doc(hit.Doc);
    Console.WriteLine($"{hit.Score:f8}" +
        $" {foundDoc.Get("name"),-15}" +
        $" {foundDoc.Get("favoritePhrase"),-40}");
}

About the project

Lucene.Net is a port of the Lucene search library, written in C# and targeted at .NET runtime users.

Latest Version - Lucene.NET 4.8.0 Beta

  • The beta version is extremely stable
  • Has more than 7800+ passing unit tests
  • Tested daily on all officially supported versions of .NET
  • Supports .NET Standard 2.1 and .NET Standard 2.0
  • Supports .NET Framework 4.6.2+
  • Some developers already use it in production environments

Our Goals

  • Maintain the existing line-by-line port from Java to C#, fully automating and commoditizing the process such that the project can easily synchronize with the Java Lucene release schedule
  • Maintaining the high-performance requirements expected of a first class C# search engine library
  • Maximize usability and power when used within the .NET runtime. To that end, it will present a highly idiomatic, carefully tailored API that takes advantage of many of the special features of the .NET runtime

Popular Books