Apache Solr 检索数据
在本章中,我们将讨论如何使用 Java Client API 检索数据。假设我们有一个名为 .csv 的文档 样本.csv 与以下内容。
001,9848022337,Hyderabad,Rajiv,Reddy 002,9848022338,Kolkata,Siddarth,Battacharya 003,9848022339,Delhi,Rajesh,Khanna
你可以在名为的核心下索引此数据 sample_Solr 使用 post command.
[Hadoop@localhost bin]$ ./post -c Solr_sample sample.csv
以下是将文档添加到 Apache Solr 索引的 Java 程序。将此代码保存在名为的文件中 检索数据.java .
import java.io.IOException; 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.SolrDocumentList; public class RetrievingData { public static void main(String args[]) throws SolrServerException, IOException { // 准备 Solr 客户端 String urlString = "http:// 本地主机:8983/Solr/my_core"; SolrClient Solr = new HttpSolrClient.Builder(urlString).build(); // 准备 Solr 查询 SolrQuery query = new SolrQuery(); query.setQuery("*:*"); // 添加要检索的字段 query.addField("*"); // 执行查询 QueryResponse queryResponse = Solr.query(query); // 存储查询结果 SolrDocumentList docs = queryResponse.getResults(); System.out.println(docs); System.out.println(docs.get(0)); System.out.println(docs.get(1)); System.out.println(docs.get(2)); // 保存操作 Solr.commit(); } }
通过在终端中执行以下命令来编译上述代码:
[Hadoop@localhost bin]$ javac RetrievingData [Hadoop@localhost bin]$ java RetrievingData
执行上述命令后,你将获得以下输出。
{numFound = 3,start = 0,docs = [SolrDocument{id=001, phone = [9848022337], city = [Hyderabad], first_name = [Rajiv], last_name = [Reddy], _version_ = 1547262806014820352}, SolrDocument{id = 002, phone = [9848022338], city = [Kolkata], first_name = [Siddarth], last_name = [Battacharya], _version_ = 1547262806026354688}, SolrDocument{id = 003, phone = [9848022339], city = [Delhi], first_name = [Rajesh], last_name = [Khanna], _version_ = 1547262806029500416}]} SolrDocument{id = 001, phone = [9848022337], city = [Hyderabad], first_name = [Rajiv], last_name = [Reddy], _version_ = 1547262806014820352} SolrDocument{id = 002, phone = [9848022338], city = [Kolkata], first_name = [Siddarth], last_name = [Battacharya], _version_ = 1547262806026354688} SolrDocument{id = 003, phone = [9848022339], city = [Delhi], first_name = [Rajesh], last_name = [Khanna], _version_ = 1547262806029500416}