Created
December 19, 2016 07:36
-
-
Save i-sync/79f98f5b250c830cbe194a878a37085a to your computer and use it in GitHub Desktop.
Lucene .Net
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class HotelSearch | |
{ | |
public static String IndexFolder => Sitecore.Configuration.Settings.DataFolder.EndsWith("\\") | |
? Sitecore.Configuration.Settings.DataFolder + "indexes\\hotel_index" | |
: Sitecore.Configuration.Settings.DataFolder + "\\indexes\\hotel_index"; | |
public void BuildIndex(HotelProperty[] datas) | |
{ | |
var dataFolder = IndexFolder; | |
if (!Directory.Exists(dataFolder)) | |
{ | |
Directory.CreateDirectory(dataFolder); | |
} | |
var analyzer = new StandardAnalyzer(Version.LUCENE_30); | |
var fs = new SimpleFSDirectory(new DirectoryInfo(dataFolder), new NoLockFactory()); | |
using (var writer = new IndexWriter(fs, analyzer, true, IndexWriter.MaxFieldLength.UNLIMITED)) | |
{ | |
var langs = LanguageCache.GetCacheData(); | |
foreach (var data in datas) | |
{ | |
var doc = new Document(); | |
doc.Add(new Field("ID", data.Id.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED)); | |
foreach (var lang in langs) | |
{ | |
doc.Add(new Field(lang.Alias + "_name", data.DisplayNames[lang.Locale], Field.Store.YES, | |
Field.Index.ANALYZED)); | |
doc.Add(new Field(lang.Alias + "_city", data.Address.CityNames[lang.Locale], Field.Store.YES, | |
Field.Index.ANALYZED)); | |
doc.Add(new Field(lang.Alias + "_country", data.Address.CountryNames[lang.Locale], Field.Store.YES, | |
Field.Index.ANALYZED)); | |
} | |
writer.AddDocument(doc); | |
} | |
writer.Optimize(); | |
writer.Flush(true, false, true); | |
writer.Dispose(); | |
} | |
} | |
public List<Guid> SearchHotel(string keywords) | |
{ | |
var analyzer = new StandardAnalyzer(Version.LUCENE_30); | |
var searcher = new IndexSearcher(new SimpleFSDirectory(new DirectoryInfo(IndexFolder))); | |
var langs = LanguageCache.GetCacheData(); | |
var list = new List<String>(); | |
foreach (var lang in langs) | |
{ | |
list.Add(lang.Alias + "_name"); | |
list.Add(lang.Alias + "_city"); | |
list.Add(lang.Alias + "_country"); | |
} | |
var parser = new MultiFieldQueryParser(Version.LUCENE_30, list.ToArray(), analyzer) | |
{ | |
DefaultOperator = QueryParser.Operator.AND | |
}; | |
var query = parser.Parse(keywords); | |
var hits = searcher.Search(query, 120); | |
return hits.ScoreDocs.OrderByDescending(x => x.Score).Select(hit => Guid.Parse(searcher.Doc(hit.Doc).Get("ID"))).ToList(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment