2012-10-22 48 views
2

如何指定SolrQuery以json格式返回數據? 下面是我用來查詢數據的代碼:一旦我得到SolrDocument,我該如何將它轉換爲json Object/string?使用solrj檢索json格式的SolrDocument

SolrQuery sQuery = new SolrQuery(); 
sQuery.setQuery("name:test"); 
QueryResponse resp = server.query(sQuery); 
SolrDocumentList docs = resp.getResults(); 

回答

3

SolrJ旨在將文檔檢索/轉換爲您定義的POJO。如果要將文檔轉換爲JSON,則需要使用類似Jackson的庫來執行從SolrDocument到JSON的轉換。

不知道這是否會成爲您的選擇,但要提及您可能會考慮從已經格式化爲JSON的Solr獲取響應。有關更多詳細信息,請參閱SolJSON。在這種情況下,您不需要使用SolrJ。最簡單的方法是直接使用http調用(通過java http客戶端庫),並使用SolJSON技術從Solr獲取JSON響應。

+0

u能請告訴我,我怎麼會指定JSON使用Java Solr的文檔檢索 - 在SolJSON文件並沒有規定如何設置Java中的請求PARAM? – rrr

+0

以前關於Solr用戶列表的討論應該有所幫助 - http://lucene.472066.n3.nabble.com/SolrJ-Response-JSON-td1002024.html –

+0

它沒有真正回答我的問題,好像我必須閱讀SolrDocument並將鍵值對添加到JSONObject中以獲取有效的json字符串以返回給用戶。關於POJO的方式,因爲我的Pojo包含複雜類型,所以我不得不將複雜類型添加爲SolrPlugin並將其定義在schema.xml中,但是當我將POJO保存爲空的複雜類型時 - 有關如何獲得該工作的任何建議? – rrr

15

導入從solrj的JSONUtil類,它有Solr的文檔JSON轉換器,或者如果你看到的那個類的代碼,你可以隨便寫一個:您還可以使用GSON

import org.apache.noggit.JSONUtil; 

SolrQuery sQuery = new SolrQuery(); 
sQuery.setQuery("name:test"); 
QueryResponse resp = server.query(sQuery); 
SolrDocumentList docs = resp.getResults(); 
String returnValue = JSONUtil.toJSON(docs); //this has the json documents 
+1

我剛剛發現了JSONUtil令人毛骨悚然併產生一些奇怪的遞歸文檔的難題。 –

0

SolrDocumentList SolrResponse = searchWithSolr(); 
 
Gson gson = new Gson(); 
 
if (SolrResponse.size()!=0) { 
 
    System.out.println(gson.toJson(SolrResponse)); 
 
    interpolMap.put("interpol", gson.toJson(InterpolSolrResponse)); 
 
}