Lucene.NET is a full-text search engine library capable of advanced text analysis, indexing, and searching. It can be used to easily add search capabilities to applications. Lucene.NET is a C# port of the popular Java Lucene search engine framework from The Apache Software Foundation, targeting the .NET platform.
using Lucene.Net.Analysis.Standard; using Lucene.Net.Documents; using Lucene.Net.Index; using Lucene.Net.Search; using Lucene.Net.Store; using Lucene.Net.Util;
// 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);
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);
// Search with a phrase var phrase = new MultiPhraseQuery { new Term("favoritePhrase", "brown"), new Term("favoritePhrase", "fox") };
// 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}"); }
See the API documentation for Lucene.NET 4.8.0.
There are several demos implemented as simple console applications that can be copied and pasted into Visual Studio or compiled on the command line in the Lucene.Net.Demo project.
There is also a dotnet command line tool available on NuGet. It contains all of the demos as well as tools maintaining your Lucene.NET index, featuring operations such as splitting, merging, listing segment info, fixing, deleting segments, upgrading, etc. Always be sure to back up your index before running any commands against it!
dotnet tool install lucene-cli -g --version 4.8.0-beta00015
NOTE: The version of the CLI you install should match the version of Lucene.NET you use.
Once installed, you can explore the commands and options that are available by entering the command lucene
.