我想在我的项目中使用Lucene搜索,因为它很快,但存在问题。
我有DB表的用户和友谊。我想通过搜索表单找到用户的好友。使用lucene,我只能通过搜索查询找到所有用户,获取他们的id,将他们放入实体框架中,然后只获取用户的好友,但如果系统中的用户有千万,而该用户的好友只有几个呢?所以我需要获取用户的好友,然后通过搜索查询进行过滤。我该怎么做?我从Lucene那里听说了Linq,但我不确定这是否是我所需要的。请帮我解决麻烦。
附言:对不起我的英语,我来自乌克兰,英语说得不好:)
我找到了解决方案。我会将好友ID存储在索引中,并通过这些ID查找用户好友。这不是最好的解决方案,因为索引会经常被编辑,但我无法实现其他想法。
这可以通过使用过滤器来实现。这是一个简短的演示,将结果限制为只有那些具有FriendsWith:Beta的文档。这需要重新编制索引受更改的友谊关系影响的文档。TermsFilter类可以在contrib包中找到。
using System;
using System.Collections.Generic;
using Lucene.Net.Analysis;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Search;
using Lucene.Net.Store;
using Directory = Lucene.Net.Store.Directory;
using Version = Lucene.Net.Util.Version;
namespace ConsoleApplication {
public static class Program {
public static void Main(string[] args) {
var directory = new RAMDirectory();
var analyzer = new KeywordAnalyzer();
using (var writer = new IndexWriter(directory, analyzer, IndexWriter.MaxFieldLength.UNLIMITED)) {
var users = new [] { "Alfa", "Beta", "Gamma", "Delta" };
var friendships = new Dictionary<String, String[]> {
{ "Alfa", new [] { "Beta", "Gamma", "Delta" } },
{ "Beta", new [] { "Gamma", "Delta" } },
{ "Gamma", new [] { "Delta" } },
{ "Delta", new String[0] } // Noone likes Delta.
};
foreach (var userName in users) {
var doc = new Document();
doc.Add(new Field("Name", userName, Field.Store.YES, Field.Index.NO));
foreach (var friendName in friendships[userName]) {
doc.Add(new Field("FriendsWith", friendName, Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
}
writer.AddDocument(doc);
}
writer.Commit();
}
// This should be the real query provided by the user (city, age, description, ...)
var query = new MatchAllDocsQuery();
// Create a filter limiting the result to those being friends with the current user,
// in this example the user "Beta".
var filter = new TermsFilter();
filter.AddTerm(new Term("FriendsWith", "Gamma"));
var reader = IndexReader.Open (directory, readOnly: true);
var searcher = new IndexSearcher(reader);
var result = searcher.Search (query, filter, 10);
foreach(var topDoc in result.ScoreDocs) {
var doc = searcher.Doc(topDoc.Doc);
var foundName = doc.Get ("Name");
Console.WriteLine("Matched user '{0}'", foundName);
}
Console.ReadLine();
}
}
}