使用 SolrJ 查詢 Solr
如果使用前面的示例將成功的文件新增到 Solr,你現在可以通過以下方式檢索它們:
package com.stackoverflow.solrj.example;
import java.io.IOException;
import java.util.Iterator;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
public class SolrJQueryExample {
private final static String SOLR_URL = "http://localhost:8983/solr/mycollection";
public static void main(String[] args) throws SolrServerException, IOException {
SolrClient solrClient = new HttpSolrClient.Builder(SOLR_URL).build();
SolrQuery solrQuery = new SolrQuery();
solrQuery.setQuery("example");
solrQuery.setStart(0);
solrQuery.setRows(10);
QueryResponse queryResponse = solrClient.query(solrQuery);
SolrDocumentList solrDocs = queryResponse.getResults();
Iterator<SolrDocument> iterator = solrDocs.iterator();
while (iterator.hasNext()) {
SolrDocument solrDocument = iterator.next();
String docId = (String) solrDocument.getFieldValue("id");
String docName = (String) solrDocument.getFieldValue("name");
System.out.println("Document " + docId + ": " + docName);
}
}
}