Created
January 13, 2014 15:56
-
-
Save BartDM/8402698 to your computer and use it in GitHub Desktop.
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
using (var searcher = new IndexSearcher(LuceneDirectory)) | |
{ | |
Log.Debug("Starting new IndexSearcher"); | |
var analyzer = new StandardAnalyzer(Version.LUCENE_30); | |
var searchResults = new SearchResult | |
{ | |
SearchTerm = searchQuery, | |
SearchResultItems = new List<SearchResultItem>() | |
}; | |
ScoreDoc[] hits; | |
if (!string.IsNullOrEmpty(field)) | |
{ | |
if (!fields.Contains(field)) | |
{ | |
throw new SearchException(string.Format("Field {0} is not a search field for type {1}", field, typeof(T))); | |
} | |
QueryParser parser = fieldsToSearchOn.Count == 1 ? | |
new QueryParser(Version.LUCENE_30, fieldsToSearchOn.First(), analyzer) : | |
new MultiFieldQueryParser(Version.LUCENE_30, fieldsToSearchOn.ToArray(), analyzer); | |
var query = ParseQuery(searchQuery, parser); | |
hits = searcher.Search(query, HitsLimit).ScoreDocs; | |
} | |
else | |
{ | |
var parser = new MultiFieldQueryParser(Version.LUCENE_30, fields.ToArray(), analyzer); | |
var query = ParseQuery(searchQuery, parser); | |
hits = searcher.Search(query, null, HitsLimit, Sort.RELEVANCE).ScoreDocs; | |
} | |
if (hits != null) | |
{ | |
Log.DebugFormat("Hits found: {0}", hits.Count()); | |
searchResults.Hits = hits.Count(); | |
foreach (var hit in hits) | |
{ | |
var doc = searcher.Doc(hit.Doc); | |
searchResults.SearchResultItems.Add(new SearchResultItem | |
{ | |
Id = Convert.ToInt32(doc.Get("Id")), | |
Score = hit.Score, | |
}); | |
} | |
} | |
else | |
{ | |
Log.DebugFormat("No hits found"); | |
} | |
analyzer.Close(); | |
searcher.Dispose(); | |
return searchResults; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment