1.Basic Applications
Using System;
Using System. Collections. Generic;
Using System. Text;
Using Lucene. Net;
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;
Using Lucene. Net. Util;
Namespace ConsoleApplication1.Lucene
{
Public class deleetest
{
Private const string FieldName = "name ";
Private const string FieldValue = "value ";
Private Directory directory = new RAMDirectory ();
Private Analyzer analyzer = new
StandardAnalyzer ();
Public
LuceneTest ()
{
}
Private void Index ()
{
IndexWriter writer = new
IndexWriter (directory, analyzer, true );
Writer. maxFieldLength = 1000;
For (int I = 1; I <= 100; I ++)
{
Document document = new
Document ();
Document. Add (new Field (FieldName, "name" + I,
Field. Store. YES, Field. Index. UN_TOKENIZED ));
Document. Add (new
Field (FieldValue, "Hello, World !",
Field. Store. YES, Field. Index. TOKENIZED ));
Writer. AddDocument (document );
}
Writer. Optimize ();
Writer. Close ();
}
Private void Search ()
{
Query query = QueryParser. Parse ("name *",
FieldName, analyzer );
IndexSearcher searcher = new IndexSearcher (directory );
Hits
Hits = searcher. Search (query );
Console. WriteLine ("qualified records: {0}; Total number of index database records: {1 }",
Hits. Length (), searcher. Reader. NumDocs ());
For (int I = 0; I <
Hits. Length (); I ++)
{
Int docId = hits. Id (I );
String name =
Hits. Doc (I). Get (FieldName );
String value =
Hits. Doc (I). Get (FieldValue );
Float score = hits. Score (I );
Console. WriteLine ("{0}: DocId: {1}; Name: {2 };
Value: {3}; Score: {4 }",
I + 1, docId, name, value,
Score );
}
Searcher. Close ();
}
}
}
Besides
RAMDirectory, you can also use
FSDirectory. (Note that when the create parameter of FSDirectory. GetDirectory is set to true, the existing index library files will be deleted. You can use IndexReader. IndexExists () to determine the value .)
Open an existing index library from the specified directory.
Private Directory directory =
FSDirectory. GetDirectory ("c: \ index", false );
Load the index library into the memory to increase the search speed.
Private Directory directory = new
RAMDirectory (FSDirectory. GetDirectory (@ "c: \ index", false ));
// Or
// Private Directory directory = new RAMDirectory (c: \ index ");
2.Multi-field search
Use MultiFieldQueryParser
You can specify multiple search fields.
Query query = MultiFieldQueryParser. Parse ("name *", new
String [] {FieldName, FieldValue}, analyzer );
IndexReader reader = IndexReader. Open (directory );
IndexSearcher searcher = new IndexSearcher (reader );
Hits hits = searcher. Search (query );
3.Multi-condition search
Besides
In addition to the complex search syntax, QueryParser. Parse can combine multiple queries.
Query query1 = new TermQuery (new Term (FieldValue,
"Name1"); // word search
Query query2 = new WildcardQuery (new Term (FieldName, "name *"); // wildcard
// Query query3 = new PrefixQuery (new Term (FieldName, "name1"); // Field search Field: Keyword, automatically added at the end *
// Query query4 = new RangeQuery (new Term (FieldNumber,
NumberTools. LongToString (11L), new Term (FieldNumber,
NumberTools. LongToString (13L), true); // range search
// Query query5 = new FilteredQuery (query, filter); // search with filter conditions
BooleanQuery query = new BooleanQuery ();
Query. Add (query1, BooleanClause. Occur. MUST );
Query. Add (query2, BooleanClause. Occur. MUST );
IndexSearcher searcher = new
IndexSearcher (reader );
Hits hits = searcher. Search (query );
4.Set weight
You can add weights (Boost) to documents and fields so that they rank top in search results. By default
Document. Score is used as the sort basis. The higher the value, the higher the ranking. The default Boost value is 1.
Score = Score * Boost
Using the formula above, we can set different weights to influence the ranking.
In the following example, different weights are set based on the VIP level.
Document document = new Document ();
Switch (vip)
{
Case VIP. Gold: document. SetBoost (2F );
Break;
Case VIP. Argentine:
Document. SetBoost (1.5F); break;
}
As long as Boost is large enough, a hit result will always rank first, which is the "billing ranking" service of Baidu and other websites. Obviously unfair.
5.Sort
Using SortField
You can set the sorting fields, sorting conditions, and inverted sorting.
Sort sort = new Sort (new SortField (FieldName,
SortField. DOC, false ));
IndexSearcher searcher = new
IndexSearcher (reader );
Hits hits = searcher. Search (query, sort );
Sorting has a great impact on search speed. Try not to use multiple sorting conditions.
6.Filter
Filter is used to Filter the search results to obtain more accurate results in a smaller range.
For example, we can search for the shelving time between--1.
To
Between-10-30.
For the date and time, we need to convert it to add it to the index database, and it must also be an index field.
// Index
Document. Add (FieldDate, DateField. DateToString (date), Field. Store. YES,
Field. Index. UN_TOKENIZED );
//...
// Search
Filter filter = new DateFilter (FieldDate, DateTime. Parse ("2005-10-1 ″),
DateTime. Parse ("2005-10-30 ″));
Hits hits = searcher. Search (query, filter );
In addition to the date and time, you can also use integers. For example, the search price is between 100 and ~ 200
Between products.
Lucene. Net NumberTools performs bitwise processing on numbers. If you need floating point numbers, you can refer to the source code.
// Index
Document. Add (new Field (FieldNumber, NumberTools. LongToString (long) price ),
Field. Store. YES, Field. Index. UN_TOKENIZED ));
//...
// Search
Filter filter = new RangeFilter (FieldNumber, NumberTools. LongToString (100L ),
NumberTools. LongToString (200L), true, true );
Hits hits = searcher. Search (query, filter );
Use Query as the filter condition.
QueryFilter filter = new
QueryFilter (QueryParser. Parse ("name2 ″,
FieldValue, analyzer ));
We can also use
FilteredQuery performs multi-condition filtering.
Filter filter = new DateFilter (FieldDate,
DateTime. Parse ("2005-10-10 ″),
DateTime. Parse ("2005-10-15 ″));
Filter filter2 = new RangeFilter (FieldNumber, NumberTools. LongToString (11L ),
NumberTools. LongToString (13L), true, true );
Query query = QueryParser. Parse ("name *",
FieldName, analyzer );
Query = new FilteredQuery (query, filter );
Query = new FilteredQuery (query, filter2 );
IndexSearcher searcher = new
IndexSearcher (reader );
Hits hits = searcher. Search (query );
7.Distributed search
We can use
MultiReader or
MultiSearcher searches for multiple index libraries.
MultiReader reader = new MultiReader (new
IndexReader [] {IndexReader. Open (@ "c: \ index "),
IndexReader. Open (@ "\ server \ index ")});
IndexSearcher searcher = new IndexSearcher (reader );
Hits hits = searcher. Search (query );
Or
IndexSearcher searcher1 = new
IndexSearcher (reader1 );
IndexSearcher searcher2 = new IndexSearcher (reader2 );
MultiSearcher searcher = new MultiSearcher (new Searchable [] {searcher1,
Searcher2 });
Hits hits = searcher. Search (query );
You can also use
ParallelMultiSearcher performs multi-thread parallel search.
8.Merge index database
Set
Merge directory1
In directory2.
Directory directory1 = FSDirectory. GetDirectory ("index1", false );
Directory directory2 = FSDirectory. GetDirectory ("index2", false );
IndexWriter writer = new IndexWriter (directory2,
Analyzer, false );
Writer. AddIndexes (new Directory [] {directory });
Console. WriteLine (writer. DocCount ());
Writer. Close ();
9.Show search syntax string
We have combined many search conditions and may want to see what the equivalent search syntax string is.
BooleanQuery query = new BooleanQuery ();
Query. Add (query1, true, false );
Query. Add (query2, true, false );
//...
Console. WriteLine ("Syntax:
{0} ", query. ToString ());
Output:
Syntax: + (name: name * value: name *) + number: [cannot exceed limit B TO exceed limit D]
It's that simple.
10.Operation index Library
Delete (soft Delete, only the delete tag is added. Call
IndexWriter. Optimize () and then delete it .)
IndexReader reader = IndexReader. Open (directory );
// Delete the Document with the specified serial number (DocId.
Reader. Delete (123 );
// Delete the Document containing the specified Term.
Reader. Delete (new Term (FieldValue, "Hello "));
// Restore soft deletion.
Reader. UndeleteAll ();
Reader. Close ();
Incremental update (you only need to set the create parameter to false to add new data to the existing index database .)
Directory directory = FSDirectory. GetDirectory ("index", false );
IndexWriter writer = new IndexWriter (directory, analyzer, false );
Writer. AddDocument (doc1 );
Writer. AddDocument (doc2 );
Writer. Optimize ();
Writer. Close ();
11.Optimization
Batch direction
Increase the merging factor (mergeFactor) when adding an index to FSDirectory
MinMergeDocs helps improve performance and reduce the indexing time.
IndexWriter writer = new IndexWriter (directory,
Analyzer, true );
Writer. maxFieldLength = 1000; // maximum field length
Writer. mergeFactor = 1000;
Writer. minMergeDocs = 1000;
For (int I = 0; I <10000; I ++)
{
// Add external entes...
}
Writer. Optimize ();
Writer. Close ();
--- Restore content end ---