问题
I am trying to sort my results in lucene
I keep getting this error however
An unhandled exception of type 'System.AccessViolationException' occurred in Search.dll
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
I have tried setting Field.Index to analysed and not analysed but no joy.
Analyzer analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29);
var parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "Title", analyzer);
Query query = parser.Parse(searchTerm.Trim() + "*");
var searcher = new IndexSearcher(directory, true);
var sortBy = new Lucene.Net.Search.Sort(new Lucene.Net.Search.SortField("Title", Lucene.Net.Search.SortField.STRING, true));
var filter = new QueryWrapperFilter(query);
// TopDocs topDocs3 = searcher.Search(query, filter, 500,sortBy);
// TopDocs topDocs = searcher.Search(query,500);
TopDocs topDocs2 = searcher.Search(query,null, 500, new Sort(new SortField("Title", SortField.STRING)));
var re = searcher.Search(query, null, 10, new Sort(new SortField("id", SortField.INT, true)));
回答1:
I have encountered the same error when trying to order my search results in LUCENE_30. I must say I wrote this example in a hurry and is not tested. What I did was the following:
string sortText = Enum.GetName(typeof(SortableFields), sortBy);
SortField field = new SortField(sortText, SortField.STRING, sortDesc);
var sortByField = new Lucene.Net.Search.Sort(field);
TopFieldCollector collector = Lucene.Net.Search.TopFieldCollector.Create(sortByField, MaxSearchResultsReturned, false, false, false, false);
using (Analyzer analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30))
{
var queryParse = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, IndexFields.FullText, analyzer);
queryParse.AllowLeadingWildcard = true;
Query query = queryParse.Parse(searchText);
using (var searcher = new IndexSearcher(directory, true))
{
searcher.Search(query, collector);
totalRows = collector.TotalHits;
TopDocs matches = collector.TopDocs(skip, take);
// convert results to known objects
var results = new List<SearchResult>();
foreach (var item in matches.ScoreDocs)
{
int id = item.Doc;
Document doc = searcher.Doc(id);
SearchResult result = new SearchResult();
result.ID = doc.GetField("ID").StringValue;
results.Add(result);
}
}
}
return results;
来源:https://stackoverflow.com/questions/26084126/lucene-net-sort-not-working-access-violation