Solr 更新文档
Apache Solr 中使用 XML 更新文档
下面给出了 XML 文件,用于更新现有文档中的一个文件。您必须使用名称 update.xml 保存此文件。
<add>
<doc>
<field name = "id">101</field>
<field name = "first name" update = "set">John</field>
<field name = "last name" update = "add">Jacob</field>
<field name = "phone" update = "add">+1499989989</field>
<field name = "city" update = "add">New York</field>
</doc>
</add>
如我们所见,上面用XML编写的文件进行更新,类似于我们以前添加的文件。但是XML和文本文档的区别在于,我们使用XML中字段的update属性。
以上文档为例,我们将尝试更新字段的字段id 为 101 的文档。
让我们以 Apache Solr 的 bin 目录中存在的 XML 文档为例。之前我们正在更新索引,该索引保存在名为 my_core 的核心中。现在,我们将使用发布工具进行更新,如下所示:
[Hadoop@localhost bin]$ ./post-c my_core update.xml
当我们编译并运行上面的命令时,我们会得到如下输出。
/home/Hadoop/java/bin/java-classpath /home/Hadoop/Solr/dist/Solr-core
6.2.0.jar-Dauto = yes-Dc = my_core-Ddata = files
org.apache.Solr.util.SimplePostTool update.xml
SimplePostTool version 5.0.0
Posting files to [base] url http://localhost:8983/Solr/my_core/update...
Entering auto mode. File endings considered are
xml,json,jsonl,csv,pdf,doc,docx,ppt,pptx,xls,xlsx,odt,odp,ods,ott,otp,ots,rtf,
htm,html,txt,log
POSTing file update.xml (application/xml) to [base]
1 files indexed.
COMMITting Solr index changes to http://localhost:8983/Solr/my_core/update...
Time spent: 0:00:00.159
验证文档
您现在可以访问Apache Solr Web 界面的主页并选择核心为my_core。我们现在将尝试在文本区域 q 中绕过查询":"检索所有文档并执行它。
使用 Java(客户端 API)更新文档
下面是 Java 程序 将文档添加到 Apache Solr 索引。您可以将此代码保存在名为 UpdatingDocument.java 的文件中。
Import java.io.IOException;
import org.apache.Solr.client.Solrj.SolrClient;
import org.apache.Solr.client.Solrj.SolrServerException;
import org.apache.Solr.client.Solrj.impl.HttpSolrClient;
import org.apache.Solr.client.Solrj.request.UpdateRequest;
import org.apache.Solr.client.Solrj.response.UpdateResponse;
import org.apache.Solr.common.SolrInputDocument;
public class UpdatingDocument {
public static void main(String args[]) throws SolrServerException, IOException {
//Preparing the Solr client
String urlString = "http://localhost:8983/Solr/my_core";
SolrClient Solr = new HttpSolrClient.Builder(urlString).build();
//Preparing the Solr document
SolrInputDocument doc = new SolrInputDocument();
UpdateRequest updateRequest = new UpdateRequest();
updateRequest.setAction( UpdateRequest.ACTION.COMMIT, false, false);
SolrInputDocument myDocumentInstantlycommited = new SolrInputDocument();
myDocumentInstantlycommited.addField("id", "002");
myDocumentInstantlycommited.addField("name", "Rahman");
myDocumentInstantlycommited.addField("age","27");
myDocumentInstantlycommited.addField("addr","hyderabad");
updateRequest.add( myDocumentInstantlycommited);
UpdateResponse rsp = updateRequest.process(Solr);
System.out.println("Documents Updated");
}
}
现在,通过在终端中执行下面给出的命令来编译上面的代码。
[Hadoop@localhost bin]$ javac UpdatingDocument
[Hadoop@localhost bin]$ java UpdatingDocument
执行上述命令会得到如下输出。