2011-09-20 62 views
1
CommonsHttpSolrServer server = new CommonsHttpSolrServer("http://localhost:8983/solr/"); 
SolrInputDocument doc1 = new SolrInputDocument(); 
doc1.addField("id", "id1"); 
doc1.addField("name", "doc1"); 
doc1.addField("price", new Float(10)); 
SolrInputDocument doc2 = new SolrInputDocument(); 
doc2.addField("id", "id1"); 
doc2.addField("name", "doc2"); 

server.add(doc1); 
server.add(doc2); 
server.commit(); 

SolrQuery query = new SolrQuery(); 
query.setQuery("id:id1"); 
query.addSortField("price", SolrQuery.ORDER.desc); 
QueryResponse rsp = server.query(query); 
Iterator<SolrDocument> iter = rsp.getResults().iterator(); 
while(iter.hasNext()){ 
    SolrDocument doc = iter.next(); 
    Collection fieldNames = doc.getFieldNames(); 
    Iterator<String> fieldIter = fieldNames.iterator(); 
    StringBuffer content = new StringBuffer(""); 
    while(fieldIter.hasNext()){ 
     String field = fieldIter.next(); 
     content.append(field+":"+doc.get(field)).append(" "); 
     //System.out.println(field); 
    } 
    System.out.println(content); 
} 

問題是我想得到結果「id:id1 name:doc2 price:10.0」,但輸出是「id:id1 name:doc2」...所以我想知道如果我想要得到結果爲「id:id1 name:doc2 price:10.0」,我該如何修改我的編程?如何更新文檔而不丟失字段?

回答

1

當您添加具有相同ID的文檔時。基本上兩次添加同一個文檔。 Solr將更新/覆蓋文檔。更新基本上是刪除和添加。

由於您使用相同ID添加的第二個文檔沒有價格字段,因此它不會被添加,您也不會找到它的索引。

當您添加回文檔時,您需要將所有字段更改並保持不變。

doc2.addField("price", new Float(10)); // should add it back to the document 
相關問題