public Esi4JRebuildSession startRebuildSession(final Class<?> type) {
return _index.execute(new Esi4JOperation<Esi4JRebuildSession>() {
@Override
public Esi4JRebuildSession execute(Client client, String indexName, OperationContext helper) {
final TypeMapping mapping = helper.findTypeMapping(type);
return new Esi4JRebuildSession() {
private final long _scrollTimeoutSeconds = 60;
private String _scrollId;
private boolean _endReached = false;
@Override
public boolean isOrdered() {
return true;
}
@Override
public Class<?> getType() {
return type;
}
/**
* only uses the batchSize from the first invocation and
* ignores changes
*/
@Override
public List<?> getNext(int batchSize) {
if (_endReached) {
// TODO improve
throw new IllegalStateException("reached end");
}
ActionFuture<SearchResponse> responseFuture;
if (_scrollId == null) {
// first request
SearchRequestBuilder builder = new SearchRequestBuilder(_client)
.setIndices(mapping.getTypeAlias()).setPostFilter(FilterBuilders.matchAllFilter())
.setScroll(TimeValue.timeValueSeconds(_scrollTimeoutSeconds))
.addSort("_id", SortOrder.ASC).setSize(batchSize);
responseFuture = _client.search(builder.request());
} else {
responseFuture = _client.searchScroll(new SearchScrollRequestBuilder(_client, _scrollId)
.request());
}
SearchResponse response = responseFuture.actionGet();
SearchHit[] hits = response.getHits().getHits();
ArrayList<Object> list = new ArrayList<Object>(hits.length);
if (hits.length == 0) {
_endReached = true;
_scrollId = null;
} else {
_scrollId = response.getScrollId();
for (int i = 0; i < hits.length; i++) {
Object o = mapping.read(hits[i]);
if (o != null) {
list.add(o);
}
}
}