如果我有预期Solr格式的单个文件(每个文件只有一个文档):
<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索引它之前修改一些字段...
发布于 2012-01-17 08:50:12
这最好是通过编程来完成的。我知道您正在寻找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()发布于 2012-01-13 01:40:45
编辑:为了将XML转换为POJO,请参考前面的SO问题- Is there a library to convert Java POJOs to and from JSON and XML?
因为已经有了预期格式的文档,所以可以只使用post.jar或post.sh脚本文件,如Solr Tutorial - Indexing Data中所示,这两个文件都接受xml文件作为输入。
此外,在SolrJ ClientUtils库中有一个toSolrInputDocument()方法可能对您有用。当然,为了使用toSolrInputDocument()方法,您需要将文件编组到SolrDocument类中。
发布于 2014-05-22 23:19:32
在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;
}https://stackoverflow.com/questions/8839331
复制相似问题