本文整理汇总了C#中Lucene.Net.Search.IndexSearcher.Explain方法的典型用法代码示例。如果您正苦于以下问题:C# IndexSearcher.Explain方法的具体用法?C# IndexSearcher.Explain怎么用?C# IndexSearcher.Explain使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Lucene.Net.Search.IndexSearcher
的用法示例。
在下文中一共展示了IndexSearcher.Explain方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: PerformExplain
/// <summary>
/// Performs the explanation.
/// </summary>
/// <param name="luceneVersion">The lucene version.</param>
/// <param name="fsDirectory">The fs directory.</param>
/// <param name="searchQuery">The search query.</param>
/// <param name="resultId">The result identifier.</param>
/// <returns></returns>
protected virtual string PerformExplain(Version luceneVersion, FSDirectory fsDirectory, string searchQuery, int resultId)
{
/*
* The obvious problem here is that we're not using the exact same search as the real one.
*/
var explanation = string.Empty;
using (var indexSearcher = new IndexSearcher(fsDirectory, false))
{
var analyzer = new StandardAnalyzer(luceneVersion);
var queryParser = new MultiFieldQueryParser(luceneVersion, new[] { "Id".ToLowerInvariant() }, analyzer)
{
DefaultOperator = QueryParser.Operator.AND
};
var query = this.searchQueryParser.ParseQuery(searchQuery, queryParser);
explanation = indexSearcher.Explain(query, resultId).ToHtml();
analyzer.Close();
}
return explanation;
}
示例2: CheckNoMatchExplanations
/// <summary>
/// Tests that all documents up to maxDoc which are *not* in the
/// expected result set, have an explanation which indicates that
/// the document does not match
/// </summary>
public static void CheckNoMatchExplanations(Query q, string defaultFieldName, IndexSearcher searcher, int[] results)
{
string d = q.ToString(defaultFieldName);
SortedSet<int?> ignore = new SortedSet<int?>();
for (int i = 0; i < results.Length; i++)
{
ignore.Add(Convert.ToInt32(results[i]));
}
int maxDoc = searcher.IndexReader.MaxDoc();
for (int doc = 0; doc < maxDoc; doc++)
{
if (ignore.Contains(Convert.ToInt32(doc)))
{
continue;
}
Explanation exp = searcher.Explain(q, doc);
Assert.IsNotNull(exp, "Explanation of [[" + d + "]] for #" + doc + " is null");
Assert.IsFalse(exp.IsMatch, "Explanation of [[" + d + "]] for #" + doc + " doesn't indicate non-match: " + exp.ToString());
}
}
示例3: GetSearcResultExplanation
private static StringBuilder GetSearcResultExplanation(LuceneQuery luceneQuery, IEnumerable<ScoreDoc> scoreDocs, IndexSearcher searcher)
{
var sb = new StringBuilder();
sb.AppendLine("Query: " + luceneQuery.Query.ToString());
foreach (var match in scoreDocs)
{
var explanation = searcher.Explain(luceneQuery.Query, match.Doc);
sb.AppendLine("-------------------");
var doc = searcher.Doc(match.Doc);
sb.AppendLine(doc.Get(Constants.TitleTag));
sb.AppendLine(explanation.ToString());
}
return sb;
}
示例4: LogResult
private void LogResult(string msg, IndexSearcher s, Query q, int doc, float? score1)
{
Log(msg + " " + score1);
Log("Explain by: " + q);
Log(s.Explain(q, doc));
}
示例5: AssertHits
/// <summary>
/// Checks to see if the hits are what we expected.
///
/// LUCENENET specific
/// Is non-static because it depends on the non-static variable, <see cref="LuceneTestCase.Similarity"/>
/// </summary>
/// <param name="query"> the query to execute </param>
/// <param name="description"> the description of the search </param>
/// <param name="expectedIds"> the expected document ids of the hits </param>
/// <param name="expectedScores"> the expected scores of the hits </param>
protected internal void AssertHits(IndexSearcher s, Query query, string description, string[] expectedIds, float[] expectedScores)
{
QueryUtils.Check(Random(), query, s, Similarity);
const float tolerance = 1e-5f;
// Hits hits = searcher.Search(query);
// hits normalizes and throws things off if one score is greater than 1.0
TopDocs topdocs = s.Search(query, null, 10000);
/*
/// // display the hits System.out.println(hits.Length() +
/// " hits for search: \"" + description + '\"'); for (int i = 0; i <
/// hits.Length(); i++) { System.out.println(" " + FIELD_ID + ':' +
/// hits.Doc(i).Get(FIELD_ID) + " (score:" + hits.Score(i) + ')'); }
/// ****
*/
// did we get the hits we expected
Assert.AreEqual(expectedIds.Length, topdocs.TotalHits);
for (int i = 0; i < topdocs.TotalHits; i++)
{
// System.out.println(i + " exp: " + expectedIds[i]);
// System.out.println(i + " field: " + hits.Doc(i).Get(FIELD_ID));
int id = topdocs.ScoreDocs[i].Doc;
float score = topdocs.ScoreDocs[i].Score;
Document doc = s.Doc(id);
Assert.AreEqual(expectedIds[i], doc.Get(FIELD_ID));
bool scoreEq = Math.Abs(expectedScores[i] - score) < tolerance;
if (!scoreEq)
{
Console.WriteLine(i + " warning, expected score: " + expectedScores[i] + ", actual " + score);
Console.WriteLine(s.Explain(query, id));
}
Assert.AreEqual(expectedScores[i], score, tolerance);
Assert.AreEqual(s.Explain(query, id).Value, score, tolerance);
}
}
示例6: TestRandom
//.........这里部分代码省略.........
Console.Write(((BytesRef)o).Utf8ToString() + " ");
}
else
{
Console.Write(o + " ");
}
}
Console.WriteLine();
}
assertNotNull(group.GroupValue);
Document parentDoc = joinS.Doc(group.GroupValue);
Console.WriteLine(" group parentID=" + parentDoc.Get("parentID") + " (docID=" + group.GroupValue + ")");
for (int hitIDX = 0; hitIDX < group.ScoreDocs.Length; hitIDX++)
{
Document doc = joinS.Doc(group.ScoreDocs[hitIDX].Doc);
//System.out.println(" score=" + group.ScoreDocs[hitIDX].Score + " childID=" + doc.Get("childID") + " (docID=" + group.ScoreDocs[hitIDX].Doc + ")");
Console.WriteLine(" childID=" + doc.Get("childID") + " child0=" + doc.Get("child0") + " (docID=" + group.ScoreDocs[hitIDX].Doc + ")");
}
}
}
}
if (results.TotalHits == 0)
{
assertNull(joinResults);
}
else
{
CompareHits(r, joinR, results, joinResults);
TopDocs b = joinS.Search(childJoinQuery, 10);
foreach (ScoreDoc hit in b.ScoreDocs)
{
Explanation explanation = joinS.Explain(childJoinQuery, hit.Doc);
Document document = joinS.Doc(hit.Doc - 1);
int childId = Convert.ToInt32(document.Get("childID"));
assertTrue(explanation.IsMatch);
assertEquals(hit.Score, explanation.Value, 0.0f);
assertEquals(string.Format("Score based on child doc range from {0} to {1}", hit.Doc - 1 - childId, hit.Doc - 1), explanation.Description);
}
}
// Test joining in the opposite direction (parent to
// child):
// Get random query against parent documents:
Query parentQuery2;
if (Random().Next(3) == 2)
{
int fieldID = Random().Next(parentFields.Length);
parentQuery2 = new TermQuery(new Term("parent" + fieldID, parentFields[fieldID][Random().Next(parentFields[fieldID].Length)]));
}
else if (Random().Next(3) == 2)
{
BooleanQuery bq = new BooleanQuery();
parentQuery2 = bq;
int numClauses = TestUtil.NextInt(Random(), 2, 4);
bool didMust = false;
for (int clauseIDX = 0; clauseIDX < numClauses; clauseIDX++)
{
Query clause;
BooleanClause.Occur occur;
if (!didMust && Random().NextBoolean())
{
occur = Random().NextBoolean() ? BooleanClause.Occur.MUST : BooleanClause.Occur.MUST_NOT;
clause = new TermQuery(RandomParentTerm(parentFields[0]));
示例7: LogResult
private void LogResult(System.String msg, IndexSearcher s, Query q, int doc, float score1)
{
QueryUtils.Check(q, s);
Log(msg + " " + score1);
Log("Explain by: " + q);
Log(s.Explain(q, doc));
}
示例8: btnExplain_Click
private void btnExplain_Click(object sender, System.EventArgs e)
{
if (listSearch.SelectedItems.Count == 0) return;
if (searchedDocIds == null || searchedDocIds.Length < listSearch.Items.Count) return;
if (_luke.IndexReader == null)
{
_luke.ShowStatus(_luke.resources.GetString("NoIndex"));
return;
}
if (query == null) return;
IndexSearcher searcher = null;
try
{
searcher = new IndexSearcher(_luke.Directory, true);
Lucene.Net.Search.Explanation expl = searcher.Explain(query, searchedDocIds[listSearch.SelectedIndices[0]]);
ExplanationDialog explDialog = new ExplanationDialog(expl);
explDialog.ShowDialog(this);
}
catch (Exception exc)
{
_luke.ErrorMessage(exc.Message);
}
finally
{
searcher.Close();
}
}
示例9: Search
public IList<ISearchResult> Search(string searchTerms, Language language, User user, ISession session)
{
var results = new List<ISearchResult>();
if (!IndexReader.IndexExists(LuceneFolder))
return results;
if (string.IsNullOrEmpty(searchTerms))
return results;
var numberOfIndexTexts = Indexer.GetNumberOfIndexedFields();
var words = searchTerms.ToLowerInvariant().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
var contentQuery = new BooleanQuery();
foreach (var keyword in words)
{
if (!string.IsNullOrEmpty(keyword))
{
var terms = new BooleanQuery();
for (int i = 0; i < numberOfIndexTexts; i++)
{
var field = string.Format("index{0}", i);
terms.Add(new WildcardQuery(new Term(field, keyword + "*")), BooleanClause.Occur.SHOULD);
}
contentQuery.Add(terms, BooleanClause.Occur.MUST);
}
}
var query = new BooleanQuery();
query.Add(contentQuery, BooleanClause.Occur.MUST);
if (user != null)
{
query.Add(new WildcardQuery(new Term("user", user.Id.ToString())), BooleanClause.Occur.MUST);
}
query.Add(new WildcardQuery(new Term("language", language.ShortName)), BooleanClause.Occur.MUST);
var searcher = new IndexSearcher(LuceneFolder);
var hits = searcher.Search(query);
if (hits.Length() == 0)
return results;
for (var i = 0; i < hits.Length(); i++)
{
var doc = hits.Doc(i);
var typeValue = doc.Get("type");
var idValue = doc.Get("id");
var type = Type.GetType(typeValue);
try
{
var searchable = (ISearchable) session.Get(type, Convert.ToInt32(idValue));
//Direct initialiseren, omdat anders die exception pas later zou kunnen komen.
NHibernateUtil.Initialize(searchable);
var title = StripTags(searchable.SearchResultTitle);
var explain = searcher.Explain(query, hits.Id(i)).ToHtml();
var result = SearchResultParser(searchable, title, explain);
if (result != null)
results.Add(result);
}
catch (ObjectNotFoundException)
{
// Misschien hier de index entry verwijderen. Omdat het object blijkbaar niet meer bestaat. Tenzij er iets anders mis is, dan
// zou verwijderen wat voorbarig zijn.
}
}
searcher.Close();
return results;
}
示例10: AddExplanation
private static string AddExplanation(IndexSearcher searcher, string data, Query query, ScoreDoc scoreDoc, IDictionary<string, int> rankings)
{
Explanation explanation = searcher.Explain(query, scoreDoc.Doc);
JObject diagnostics = new JObject();
int rankVal;
string id = searcher.Doc(scoreDoc.Doc).Get("Id");
if (rankings.TryGetValue(id, out rankVal))
{
float rankingScore = RankingScoreQuery.GetRankingScore(rankings, id);
diagnostics.Add("Rank", rankVal);
diagnostics.Add("RankScore", rankingScore);
diagnostics.Add("LuceneScore", scoreDoc.Score / rankingScore);
}
diagnostics.Add("Score", scoreDoc.Score.ToString());
diagnostics.Add("Explanation", explanation.ToString());
diagnostics.Add("IdTerms", GetTerms(searcher, scoreDoc.Doc, "Id"));
diagnostics.Add("TokenizedIdTerms", GetTerms(searcher, scoreDoc.Doc, "TokenizedId"));
diagnostics.Add("ShingledIdTerms", GetTerms(searcher, scoreDoc.Doc, "ShingledId"));
diagnostics.Add("VersionTerms", GetTerms(searcher, scoreDoc.Doc, "Version"));
diagnostics.Add("TitleTerms", GetTerms(searcher, scoreDoc.Doc, "Title"));
diagnostics.Add("TagsTerms", GetTerms(searcher, scoreDoc.Doc, "Tags"));
diagnostics.Add("DescriptionTerms", GetTerms(searcher, scoreDoc.Doc, "Description"));
diagnostics.Add("AuthorsTerms", GetTerms(searcher, scoreDoc.Doc, "Authors"));
diagnostics.Add("OwnersTerms", GetTerms(searcher, scoreDoc.Doc, "Owners"));
diagnostics.Add("PublishedDate", GetInt(searcher, scoreDoc.Doc, "PublishedDate"));
diagnostics.Add("EditedDate", GetInt(searcher, scoreDoc.Doc, "EditedDate"));
diagnostics.Add("CuratedFeed", GetMultiValue(searcher, scoreDoc.Doc, "CuratedFeed"));
diagnostics.Add("Key", GetInt(searcher, scoreDoc.Doc, "Key"));
diagnostics.Add("Checksum", GetInt(searcher, scoreDoc.Doc, "Checksum"));
diagnostics.Add("ProjectGuidRankings", GetProjectGuidRankings(searcher, scoreDoc.Doc));
JObject obj = JObject.Parse(data);
obj.Add("diagnostics", diagnostics);
data = obj.ToString();
return data;
}
示例11: AutoCompleteMakeResult
public static JToken AutoCompleteMakeResult(IndexSearcher searcher, TopDocs topDocs, int skip, int take, NuGetSearcherManager searcherManager, bool includeExplanation, Query query)
{
JArray array = new JArray();
for (int i = skip; i < Math.Min(skip + take, topDocs.ScoreDocs.Length); i++)
{
ScoreDoc scoreDoc = topDocs.ScoreDocs[i];
Document document = searcher.Doc(scoreDoc.Doc);
string id = document.Get("Id");
array.Add(id);
}
JObject result = new JObject();
result.Add("@context", new JObject { { "@vocab", "http://schema.nuget.org/schema#" } });
result.Add("totalHits", topDocs.TotalHits);
result.Add("indexName", searcherManager.IndexName);
result.Add("data", array);
if (includeExplanation)
{
JArray explanations = new JArray();
for (int i = skip; i < Math.Min(skip + take, topDocs.ScoreDocs.Length); i++)
{
ScoreDoc scoreDoc = topDocs.ScoreDocs[i];
Explanation explanation = searcher.Explain(query, scoreDoc.Doc);
explanations.Add(explanation.ToString());
}
result.Add("explanations", explanations);
}
return result;
}
示例12: ExtrairExplicacaoQueryComTermoPorCidade
public void ExtrairExplicacaoQueryComTermoPorCidade(Directory diretorio, Query query)
{
using (var indexSearcher = new IndexSearcher(diretorio, true))
{
var topDocs = indexSearcher.Search(query, 10);
foreach (var scoreDoc in topDocs.ScoreDocs)
{
var explanation = indexSearcher.Explain(query, scoreDoc.Doc);
var document = indexSearcher.Doc(scoreDoc.Doc);
Console.WriteLine("------\n{0}\n{1}", document.Get(TipoImovel), explanation);
}
}
}
示例13: MakeResultData
public static JToken MakeResultData(IndexSearcher searcher, string currentOwner, string scheme, TopDocs topDocs, int skip, int take, SecureSearcherManager searcherManager, bool includeExplanation, Query query)
{
Uri registrationBaseAddress = searcherManager.RegistrationBaseAddress[scheme];
JArray array = new JArray();
for (int i = skip; i < Math.Min(skip + take, topDocs.ScoreDocs.Length); i++)
{
ScoreDoc scoreDoc = topDocs.ScoreDocs[i];
Document document = searcher.Doc(scoreDoc.Doc);
string url = document.Get("Url");
string id = document.Get("Id");
string version = document.Get("Version");
string owner = document.Get("Owner");
string ns = document.Get("Namespace");
if (ns != null)
{
id = string.Format("{0}.{1}", ns, id);
}
JObject obj = new JObject();
obj["@id"] = new Uri(registrationBaseAddress, url).AbsoluteUri;
obj["@type"] = document.Get("@type");
obj["registration"] = new Uri(registrationBaseAddress, string.Format("{0}/index.json", id.ToLowerInvariant())).AbsoluteUri;
obj["id"] = id;
obj["isOwner"] = (owner == currentOwner);
ServiceHelpers.AddField(obj, document, "packageContent", "PackageContent");
ServiceHelpers.AddField(obj, document, "catalogEntry", "CatalogEntry");
ServiceHelpers.AddFieldBool(obj, document, "listed", "Listed");
ServiceHelpers.AddField(obj, document, "tenantId", "TenantId");
ServiceHelpers.AddField(obj, document, "namespace", "Namespace");
ServiceHelpers.AddField(obj, document, "visibility", "Visibility");
ServiceHelpers.AddField(obj, document, "description", "Description");
ServiceHelpers.AddField(obj, document, "summary", "Summary");
ServiceHelpers.AddField(obj, document, "title", "Title");
ServiceHelpers.AddField(obj, document, "iconUrl", "IconUrl");
ServiceHelpers.AddField(obj, document, "homepage", "Homepage");
ServiceHelpers.AddField(obj, document, "licenseUrl", "LicenseUrl");
ServiceHelpers.AddField(obj, document, "projectUrl", "ProjectUrl");
ServiceHelpers.AddFieldAsObject(obj, document, "license", "LicenseDetails");
ServiceHelpers.AddFieldAsObject(obj, document, "owner", "OwnerDetails");
ServiceHelpers.AddFieldAsArray(obj, document, "tags", "Tags");
ServiceHelpers.AddFieldAsArray(obj, document, "authors", "Authors");
ServiceHelpers.AddFieldAsArray(obj, document, "categories", "Categories");
obj["version"] = version;
obj["versions"] = searcherManager.GetVersions(scheme, scoreDoc.Doc);
if (includeExplanation)
{
Explanation explanation = searcher.Explain(query, scoreDoc.Doc);
obj["explanation"] = explanation.ToString();
}
array.Add(obj);
}
return array;
}