使用 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);
        }

    }
}