-
Notifications
You must be signed in to change notification settings - Fork 1
/
MySearch.cs
201 lines (171 loc) · 5.4 KB
/
MySearch.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
using System;
using System.Collections.Generic;
using System.Text;
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Miscellaneous;
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.QueryParsers.Classic;
using Lucene.Net.Search;
using Lucene.Net.Store;
using Lucene.Net.Util;
using LuceneNet48Demo.DO;
namespace LuceneNet48Demo
{
/// <summary>
/// lucene.net based search
/// </summary>
public class MySearch
{
private const LuceneVersion MATCH_LUCENE_VERSION = LuceneVersion.LUCENE_48;
private readonly IndexWriter _writer;
private readonly SearcherManager _searchManager;
private readonly Analyzer _analyzer;
private readonly QueryParser _queryParser;
public MySearch(string indexPath)
{
//_analyzer = new EnhEnglishAnalyzer(MATCH_LUCENE_VERSION);
_analyzer = new MultiFieldAnalyzerWrapper(
defaultAnalyzer: new EnhEnglishAnalyzer(MATCH_LUCENE_VERSION, true),
new[]
{
(
new[] { "genre", "year" },
Analyzer.NewAnonymous(createComponents: (fieldName, reader) =>
{
var source = new KeywordTokenizer(reader);
TokenStream result = new ASCIIFoldingFilter(source);
result = new LowerCaseFilter(MATCH_LUCENE_VERSION, result);
return new TokenStreamComponents(source, result);
})
)
});
_writer = new IndexWriter(FSDirectory.Open(indexPath), new IndexWriterConfig(MATCH_LUCENE_VERSION, _analyzer));
_searchManager = new SearcherManager(_writer, true, null);
// make alias for fields: "t" -> "title"; "s" -> "summary"
_queryParser = new AliasMultiFieldQueryParser(MATCH_LUCENE_VERSION, new[] { "title", "sumary" }, _analyzer,
new Dictionary<string, string>()
{
{ "t", "title" },
{ "s", "summary" }
});
}
/// <summary>
/// create index
/// </summary>
public void Index()
{
const string keyField = "id";
foreach (var movie in MovieDatabase.Database)
{
// prapare new document
var doc = new Document
{
new StringField(keyField, $"{movie.Id}", Field.Store.YES),
new TextField("title", movie.Title, Field.Store.YES),
new TextField("summary", movie.Summary, Field.Store.YES),
new StringField("genre", movie.Genre, Field.Store.YES),
new Int32Field("year", movie.Year, Field.Store.YES),
};
foreach (var actor in movie.Actors)
{
doc.Add(new TextField("actor", actor, Field.Store.YES));
}
// https://stackoverflow.com/questions/26094224/lucene-net-update-data
// Where in Term constructor field "ID" is my unique field with no index flag and Value
// is text of old value field "ID" in old document in index.
_writer.UpdateDocument(new Term(keyField, doc.GetField(keyField).GetStringValue()), doc);
// for debug Analyzer work use this ...
PrintTokens(_writer.Analyzer, "title", movie.Title);
}
// https://stackoverflow.com/questions/44181550/c-sharp-lucene-net-indexwriter-deletedocuments-not-working/54336227#54336227
// Delete last movie, check DeleteDocuments() principle
_writer.DeleteDocuments(new Term(keyField, "7"));
_writer.Flush(true, true);
_writer.Commit();
}
/// <summary>
/// search index
/// </summary>
public SearchResults Search(string query)
{
// Execute the search with a fresh indexSearcher
_searchManager.MaybeRefreshBlocking();
var searcher = _searchManager.Acquire();
try
{
var q = _queryParser.Parse(query);
var topDocs = searcher.Search(q, 10);
var result = new SearchResults()
{
Query = query,
TotalHits = topDocs.TotalHits,
};
foreach (var scoreDoc in topDocs.ScoreDocs)
{
var document = searcher.Doc(scoreDoc.Doc);
var hit = new MovieHit
{
Id = int.Parse(document.GetField("id")?.GetStringValue()),
Title = document.GetField("title")?.GetStringValue(),
Summary = document.GetField("summary")?.GetStringValue(),
Genre = document.GetField("genre")?.GetStringValue(),
Year = document.GetField("year")?.GetInt32Value(),
// Results are automatically sorted by relevance
Score = scoreDoc.Score,
};
result.Hits.Add(hit);
}
return result;
}
finally
{
_searchManager.Release(searcher);
searcher = null;
}
}
/// <summary>
/// reading index document by document
/// </summary>
public void WorkOnIndex()
{
// I. do by Document Id
var reader = _writer.GetReader(true);
for (var x = 0; x < reader.NumDocs; x++)
{
var doc = reader.Document(x);
// do something ...
}
// II. use term & selected fields
_writer.ForEachTermDocs(new Term("year", "1194"), new[] { "title" }, d =>
{
var title = d.GetField("title").GetStringValue();
// do something ...
});
}
/// <summary>
/// print tokens after field analyze
/// </summary>
protected void PrintTokens(Analyzer analyzer, string fieldName, string text)
{
if (analyzer == null)
throw new ArgumentNullException(nameof(analyzer));
var tokenStream = analyzer.GetTokenStream(fieldName, text);
var termAttr = tokenStream.GetAttribute<ICharTermAttribute>();
tokenStream.Reset();
var str = new StringBuilder();
while (tokenStream.IncrementToken())
{
if (str.Length > 0)
{
str.Append(" ");
}
str.Append(termAttr.ToString());
}
Console.WriteLine($"field: {fieldName} '{text}' -> '{str.ToString()}'");
tokenStream.Reset();
}
}
}