摘要:Lucene.Net 解決 a071,a072,a073 檢索問題
在這裡我們會用幾種方式解決下列問題 :
找出第二張 Table 的 Stores 欄位有哪些資料列包含第一張 Table 的 Stores 欄位
Table : TEMP_STORES
STORES |
---|
a001 |
a002 |
b003 |
a003 |
a003 |
a001 |
a002 |
a001 |
a001,a002,a003 |
Table : STORES
ID | STORES |
---|---|
SD12340 | a001,a002,a003 |
SD12341 | a001,a002,a003 |
SD12342 | b001,b002,b003 |
SD12343 | a001,a002,a003 |
SD12344 | a001,a002,a003 |
SD12346 | a001,a002,a003 |
SD12347 | a001,a002,a003 |
SD12348 | a001,a002,a003 |
SD12349 |
a001,a002,a003
|
使用一般 SQL :
這裡我們會需要用到可以分割 a071,a072,a073 這樣字串的 Function , 可以把它分割成如第一張 Table ,
然後再使用 CROSS APPLY
CROSS APPLY dbo.fn_slip_str(Stores.Stores,',')
使用全文檢索 :
若我們要搜尋 Stores 包含 a001 這個字串
select * from Stores
WHERE CONTAINS(Stores,'a001')
使用Lucene.Net :
Step 1 : Build RAMDirectory
static RAMDirectory dir = new RAMDirectory();
Step 2 : Build Index
在建立 Index 時以空白取代逗點 , 如 Line 13
private void BuildIndex()
{
IndexWriter iw = new IndexWriter(dir, new StandardAnalyzer(Version.LUCENE_30), true, IndexWriter.MaxFieldLength.UNLIMITED);
Document doc = new Document();
doc.Add(new Field("PROD_ID", "", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.NO));
doc.Add(new Field("PROD_Name", "", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.NO));
for (int i = 1; i <= 10; i++)
{
doc.GetField("PROD_ID").SetValue(i.ToString());
doc.GetField("PROD_Name").SetValue("a072 a071 a08" + i.ToString());
iw.AddDocument(doc);
}
iw.Optimize();
iw.Commit();
iw.Close();
}
Step 3 : Search
private void SearchIndex(string KeyWord)
{
IndexSearcher search = new IndexSearcher(dir, true);
QueryParser qp = new QueryParser(Version.LUCENE_30, "PROD_Name", new WhitespaceAnalyzer());
Query query = qp.Parse(KeyWord);
var hits = search.Search(query, null, search.MaxDoc).ScoreDocs;
foreach (var res in hits)
{
Response.Write(string.Format("PROD_ID:{0} / PROD_Name{1}", search.Doc(res.Doc).Get("PROD_ID").ToString()
, search.Doc(res.Doc).Get("PROD_Name").ToString() + "
"));
}
}
Step 4 : 執行
BuildIndex();
SearchIndex("a083");
Result :
PROD_ID:3 / PROD_Namea072 a071 a083