2012-11-30 40 views
2

我真的在爲這個新API而努力,並且缺乏像NRT Manager這樣的核心內容的例子。Lucene 4.0 API - NRTManager簡單案例使用

我跟着this例子,這裏是最後的結果是:

這是怎樣的NRT經理建:

analyzer = new StopAnalyzer(Version.LUCENE_40); 
config = new IndexWriterConfig(Version.LUCENE_40, analyzer); 
writer = new IndexWriter(FSDirectory.open(new File(ConfigUtil.getProperty("lucene.directory"))), config); 
mgrWriter = new NRTManager.TrackingIndexWriter(writer); 
ReferenceManager<IndexSearcher> mgr = new NRTManager(mgrWriter, new SearcherFactory(), true); 

添加新的元素到NRT經理的作家:

long gen = -1; 
try{ 
    Document userDoc = DocumentManager.getDocument(user); 
    gen = mgrWriter.addDocument(userDoc); 
} catch (Exception e) {} 
return gen; 

經過一段時間我需要更新以前的文檔:

// Acquire a searcher from the NRTManager. I am using the generation obtained in the creation step 
((NRTManager)mgr).waitForGeneration(gen); 
searcher = mgr.acquire(); 

//Search for the document based on some user id 
Term idTerm = new Term(USER_ID, Integer.toString(userId)); 
Query idTermQuery = new TermQuery(term); 
TopDocs result = searcher.search(idTermQuery, 1); 
if (result.totalHits > 0) resultDoc = searcher.doc(result.scoreDocs[0].doc); 
else resultDoc = null; 

問題是resultDoc將始終爲空。我錯過了什麼?我不應該使用commit()flush()來查看這些更改。我正在使用NRTManagerReopenThread,例如here

LE userDoc創作

public static Document getDocument(User user) { 
    Document doc = new Document(); 
    FieldType storedType = new FieldType(); 
    storedType.setStored(true); 
    storedType.setIndexed(false); 

    // Store user data 
    doc.add(new Field(USER_ID, user.getId().toString(), storedType)); 
    doc.add(new Field(USER_NAME, user.getFirstName() + user.getLastName(), storedType)); 

    FieldType unstoredType = new FieldType(); 
    unstoredType.setStored(false); 
    unstoredType.setIndexed(true); 
    Field field = null; 

    // Analyze Location 
    String tokens = ""; 
    if (user.getLocation() != null && ! user.getLocation().isEmpty()){ 
     for (Tag location : user.getLocation()) tokens += location.getName() + " "; 

     field = new Field(USER_LOCATION, tokens, unstoredType); 
     field.setBoost(Constants.LOCATION); 
     doc.add(field); 
    } 

    // Analyze Language 
    if (user.getLanguage() != null && ! user.getLanguage().isEmpty()){ 
     // Same as Location 
} 

    // Analyze Career 
    if (user.getCareer() != null && ! user.getCareer().isEmpty()){ 
     // Same as Location 
    } 
    return doc; 
} 
+0

什麼是IndexAccess? getManagerWriter如何實現? mgrWriter在哪裏實例化?你能提供一個獨立的例子,除了Lucene之外沒有別的問題嗎? – jpountz

+0

@jpountz嗨!我編輯了代碼。我希望現在清楚。 – Ionut

+0

它在這裏完美運作。 userDoc是如何創建的? – jpountz

回答

1

你的問題不是NRT相關。您正在重新搜索USER_ID字段,儘管它尚未編入索引,但這不起作用。如果你不希望你的ID字段被標記,只需調用FieldType#setTokenized(false)(或者只是使用StringField,默認情況下它的確如此:未經標記化索引)。