Apache Solr – 更新数据
Apache Solr – 更新数据
使用 XML 更新文档
以下是用于更新现有文档中的字段的 XML 文件。将其保存在名为update.xml的文件中。
<add>
<doc>
<field name = "id">001</field>
<field name = "first name" update = "set">Raj</field>
<field name = "last name" update = "add">Malhotra</field>
<field name = "phone" update = "add">9000000000</field>
<field name = "city" update = "add">Delhi</field>
</doc>
</add>
正如您所看到的,用于更新数据的 XML 文件就像我们用来添加文档的文件一样。但唯一的区别是我们使用了字段的更新属性。
在我们的示例中,我们将使用上述文档并尝试更新 id 为001的文档字段。
假设 XML 文档存在于Solr的bin目录中。由于我们正在更新名为my_core的核心中存在的索引,因此您可以使用post工具进行更新,如下所示 –
[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)更新文档
以下是将文档添加到 Apache Solr 索引的 Java 程序。将此代码保存在名为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
执行上述命令后,您将获得以下输出。
Documents updated