如何从solr中选择使用java?

时间:2014-11-19 09:07:40

标签: java solr

我在solr中保存数据:

String solrUrl = "http://localhost:8984/solr";
SolrServer solrServer = new HttpSolrServer( solrUrl );
SolrInputDocument doc = new SolrInputDocument();
doc.addField("id", "1");
doc.addField("first_name", "Ann");
doc.addField("last_name", "Smit");
doc.addField("email", "test@test.com");
try {
   solrServer.add(doc);
   solrServer.commit();
} catch (SolrServerException e) {/* */}

从solr中选择数据:

SolrQuery query = new SolrQuery();
query.setQuery("*:*");
query.addFilterQuery("first_name:Ann*");
query.addFilterQuery("last_name:Ann*");
query.setFields("id","first_name","last_name","email");
QueryResponse response = null;
try {
    response = solrServer.query(query);
} catch (SolrServerException e) {/* */ }
SolrDocumentList list = response.getResults();

我有搜索条件:名字姓氏应包含值Ann。如何为选择保存的数据设置FilterQuery

2 个答案:

答案 0 :(得分:1)

应该使用:

SolrQuery parameters = new SolrQuery();
query.setQuery("first_name:qwe2 OR last_name:qwe2");
query.setFields("id","first_name","last_name","email");
QueryResponse response = null;
try {
    response = solrServer.query(parameters);
} catch (SolrServerException e) {/* */ }
SolrDocumentList list = response.getResults();

答案 1 :(得分:0)

使用SolrJ搜索

import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;

import java.net.MalformedURLException;
public class SolrJSearcher {
  public static void main(String[] args) throws MalformedURLException, SolrServerException {
    HttpSolrServer solr = new HttpSolrServer("url");

    SolrQuery query = new SolrQuery();
    query.setQuery("sony digital camera");
    query.addFilterQuery("cat:electronics","store:amazon.com");
    query.setFields("id","price","merchant","cat","store");
    query.setStart(0);    
    query.set("defType", "edismax");

    QueryResponse response = solr.query(query);
    SolrDocumentList results = response.getResults();
    for (int i = 0; i < results.size(); ++i) {
      System.out.println(results.get(i));
    }
  }
}