一开始不清楚的情况下,就测试建立索引,然后发现每次提交第二条索引数据时就报错:
Exception in thread "main" org.apache.solr.client.solrj.impl.CloudSolrServer$RouteException: Document contains multiple values for uniqueKey field: id=[8b0d6c35-975e-4943-b1e0-2f0eca7cfee0, 2c904eee-fdf4-448c-a3f5-98cfb29daef9]
通过错误提示,就是id是个唯一值,但是提交时出现的id是多值,下面是我第一次测试的代码:
public static void solrBatchInsertIndex(List<Map<String, String>> dataMap,
SolrServer solrServer) {
Collection<SolrInputDocument> solrDocs = new ArrayList<SolrInputDocument>();
SolrInputDocument solrInputDoc = new SolrInputDocument();
try {
// 遍历多条记录(多个rowkey)
for (int i = 0; i < dataMap.size(); i++) {
Set<Entry<String, String>> docMaps = dataMap.get(i).entrySet();
if (!docMaps.isEmpty()) {
for (Entry<String, String> entry : docMaps) {
String column = entry.getKey();
String values = entry.getValue();
solrInputDoc.addField(column, values);
}
solrServer.add(solrInputDoc);
solrServer.commit(waitFlush, waitSearcher, softCommit);
}
}
} catch (SolrServerException e) {
logger.error(e.getMessage());
} catch (IOException e) {
logger.error(e.getMessage());
}
}
后来跟踪调试发现,solrInputDoc对象在上一次提交完没有清空导致的。调整后的正确代码如下:
public static void solrBatchInsertIndex(List<Map<String, String>> dataMap,
SolrServer solrServer) {
Collection<SolrInputDocument> solrDocs = new ArrayList<SolrInputDocument>();
SolrInputDocument solrInputDoc = new SolrInputDocument();
try {
// 遍历多条记录(多个rowkey)
for (int i = 0; i < dataMap.size(); i++) {
Set<Entry<String, String>> docMaps = dataMap.get(i).entrySet();
if (!docMaps.isEmpty()) {
for (Entry<String, String> entry : docMaps) {
String column = entry.getKey();
String values = entry.getValue();
solrInputDoc.addField(column, values);
}
solrServer.add(solrInputDoc);
solrServer.commit(waitFlush, waitSearcher, softCommit);
solrInputDoc.clear();
}
}
} catch (SolrServerException e) {
logger.error(e.getMessage());
} catch (IOException e) {
logger.error(e.getMessage());
}
}