![](/img/trans.png)
[英]How to Index String with XML or JSON in Solr without using SolrInputDocument
[英]parse Solr xml files to SolrInputDocument
如果我有预期的Solr格式的单个文件(每个文件只有一个doc):
<add>
<doc>
<field name="id">GB18030TEST</field>
<field name="name">Test with some GB18030 encoded characters</field>
<field name="features">No accents here</field>
<field name="features">ÕâÊÇÒ»¸ö¹¦ÄÜ</field>
<field name="price">0</field>
</doc>
</add>
有没有办法轻松地将该文件封送到SolrInputDocument? 我自己必须解析吗?
编辑:我需要它在java pojo中因为我想在使用SolrJ索引它之前修改一些字段...
编辑:为了将XML转换为POJO,请参考此前的SO问题 - 是否有一个库将Java POJO转换为JSON和XML?
由于您已经拥有预期格式的文档,因此您可以使用post.jar或post.sh脚本文件,如Solr教程 - 索引数据中所示 ,它们都接受xml文件作为输入。
此外,SolrJ ClientUtils库中有一个toSolrInputDocument()方法,可能对您有用。 当然,您需要将文件封送到SolrDocument类中,以便使用toSolrInputDocument()
方法。
在Java中,您可以这样做。
private void populateIndexFromXmlFile(String fileName) throws Exception {
UpdateRequest update = new UpdateRequest();
update.add(getSolrInputDocumentListFromXmlFile(fileName));
update.process(server);
server.commit();
}
private List<SolrInputDocument> getSolrInputDocumentListFromXmlFile(
String fileName) throws Exception {
ArrayList<SolrInputDocument> solrDocList = new ArrayList<SolrInputDocument>();
File fXmlFile = new File(fileName);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
NodeList docList = doc.getElementsByTagName("doc");
for (int docIdx = 0; docIdx < docList.getLength(); docIdx++) {
Node docNode = docList.item(docIdx);
if (docNode.getNodeType() == Node.ELEMENT_NODE) {
SolrInputDocument solrInputDoc = new SolrInputDocument();
Element docElement = (Element) docNode;
NodeList fieldsList = docElement.getChildNodes();
for (int fieldIdx = 0; fieldIdx < fieldsList.getLength(); fieldIdx++) {
Node fieldNode = fieldsList.item(fieldIdx);
if (fieldNode.getNodeType() == Node.ELEMENT_NODE) {
Element fieldElement = (Element) fieldNode;
String fieldName = fieldElement.getAttribute("name");
String fieldValue = fieldElement.getTextContent();
solrInputDoc.addField(fieldName, fieldValue);
}
}
solrDocList.add(solrInputDoc);
}
}
return solrDocList;
}
这最好以编程方式完成。 我知道你正在寻找一个Java解决方案,但我个人推荐groovy。
以下脚本处理当前目录中的XML文件。
//
// Dependencies
// ============
import org.apache.solr.client.solrj.SolrServer
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer
import org.apache.solr.common.SolrInputDocument
@Grapes([
@Grab(group='org.apache.solr', module='solr-solrj', version='3.5.0'),
])
//
// Main
// =====
SolrServer server = new CommonsHttpSolrServer("http://localhost:8983/solr/");
new File(".").eachFileMatch(~/.*\.xml/) {
it.withReader { reader ->
def xml = new XmlSlurper().parse(reader)
xml.doc.each {
SolrInputDocument doc = new SolrInputDocument();
it.field.each {
doc.addField(it.@name.text(), it.text())
}
server.add(doc)
}
}
}
server.commit()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.