用好Collection<SolrInputDocument>对solrj入库进行优化

今天一个朋友找我说他进行入库测试:1 个 collection,2 个 shard,30 多个字段,一个小时才入库 4 万条左右。

如果每条记录都很大这也是有可能的,不过我还是先让他贴代码出来看一下,他的入库代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static void addIndex(String record) throws SolrServerException, IOException {
String[] records = record.split("\\\\+\\", -1);

SolrInputDocument doc = new SolrInputDocument();
doc.addField("id", uuid(), 1.0f);
doc.addField("DATA0", records[0], 1.0f);
// ...
doc.addField("DATA31", records[31], 1.0f);

Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
docs.add(doc);
server.add(docs);
server.commit();
}

优化建议

这样一条一条提交显然会慢的,除非要保证较强的事务性或者实时性,我建议他进行批量入库,类似这样:

1
2
3
4
5
6
7
8
9
10
11
Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();

for (j = 0; j < 100000; j++) {
SolrInputDocument doc = new SolrInputDocument();
doc.setField("id", "i_" + i + 1 + "_j_" + j + 1 + "_" + ((i + 1) * (j + 1)));
doc.setField("type", j % 7);
doc.setField("name", "name" + System.currentTimeMillis());
docs.add(doc);
}
server.add(docs);
server.commit();

配置自动提交

另外一点,如果我们能够控制好输入的速度,可以考虑 autocommit,比如在 solrconfig.xml 里面配置:

1
2
3
4
5
<autoCommit>
<maxTime>15000</maxTime>
<maxDocs>10000</maxDocs>
<openSearcher>true</openSearcher>
</autoCommit>

上面配置的意思是:

  • maxTime: 每 15000ms,自动进行一次 commit
  • maxDocs: 若超过 10000 个文档更新,自动进行一次 commit
  • openSearcher: 执行完 commit 后记录马上可以搜索到
© 2025 Solr Community of China All Rights Reserved. 本站访客数人次 本站总访问量
Theme by hiero