Search in sources :

Example 46 with BulkResponse

use of org.elasticsearch.action.bulk.BulkResponse in project metacat by Netflix.

the class ElasticSearchUtilImpl method updateDocs.

private void updateDocs(final String type, final List<String> ids, final ObjectNode node) {
    try {
        RETRY_ES_PUBLISH.call(() -> {
            final BulkRequestBuilder bulkRequest = client.prepareBulk();
            ids.forEach(id -> {
                bulkRequest.add(client.prepareUpdate(esIndex, type, id).setRetryOnConflict(NO_OF_CONFLICT_RETRIES).setDoc(metacatJson.toJsonAsBytes(node), XContentType.JSON));
            });
            final BulkResponse bulkResponse = bulkRequest.execute().actionGet(esBulkCallTimeout);
            if (bulkResponse.hasFailures()) {
                for (BulkItemResponse item : bulkResponse.getItems()) {
                    if (item.isFailed()) {
                        handleException("ElasticSearchUtil.updateDocs.item", type, item.getId(), item.getFailure().getCause(), Metrics.CounterElasticSearchUpdate.getMetricName());
                    }
                }
            }
            return null;
        });
    } catch (Exception e) {
        handleException("ElasticSearchUtil.updatDocs", type, ids, e, Metrics.CounterElasticSearchBulkUpdate.getMetricName());
    }
}
Also used : BulkItemResponse(org.elasticsearch.action.bulk.BulkItemResponse) BulkResponse(org.elasticsearch.action.bulk.BulkResponse) BulkRequestBuilder(org.elasticsearch.action.bulk.BulkRequestBuilder) FailedNodeException(org.elasticsearch.action.FailedNodeException) RetryException(com.github.rholder.retry.RetryException) NodeClosedException(org.elasticsearch.node.NodeClosedException) ReceiveTimeoutTransportException(org.elasticsearch.transport.ReceiveTimeoutTransportException) NoNodeAvailableException(org.elasticsearch.client.transport.NoNodeAvailableException) TransportException(org.elasticsearch.transport.TransportException) ElasticsearchTimeoutException(org.elasticsearch.ElasticsearchTimeoutException) EsRejectedExecutionException(org.elasticsearch.common.util.concurrent.EsRejectedExecutionException)

Example 47 with BulkResponse

use of org.elasticsearch.action.bulk.BulkResponse in project metacat by Netflix.

the class ElasticSearchUtilImpl method hardDeleteDoc.

/**
 * Permanently delete index documents.
 *
 * @param type index type
 * @param ids  entity ids
 */
private void hardDeleteDoc(final String type, final List<String> ids) {
    try {
        RETRY_ES_PUBLISH.call(() -> {
            final BulkRequestBuilder bulkRequest = client.prepareBulk();
            ids.forEach(id -> bulkRequest.add(client.prepareDelete(esIndex, type, id)));
            final BulkResponse bulkResponse = bulkRequest.execute().actionGet(esBulkCallTimeout);
            log.info("Deleting metadata of type {} with count {}", type, ids.size());
            if (bulkResponse.hasFailures()) {
                for (BulkItemResponse item : bulkResponse.getItems()) {
                    if (item.isFailed()) {
                        handleException("ElasticSearchUtil.bulkDelete.item", type, item.getId(), item.getFailure().getCause(), Metrics.CounterElasticSearchDelete.getMetricName());
                    }
                }
            }
            return null;
        });
    } catch (Exception e) {
        handleException("ElasticSearchUtil.bulkDelete", type, ids, e, Metrics.CounterElasticSearchBulkDelete.getMetricName());
    }
}
Also used : BulkItemResponse(org.elasticsearch.action.bulk.BulkItemResponse) BulkResponse(org.elasticsearch.action.bulk.BulkResponse) BulkRequestBuilder(org.elasticsearch.action.bulk.BulkRequestBuilder) FailedNodeException(org.elasticsearch.action.FailedNodeException) RetryException(com.github.rholder.retry.RetryException) NodeClosedException(org.elasticsearch.node.NodeClosedException) ReceiveTimeoutTransportException(org.elasticsearch.transport.ReceiveTimeoutTransportException) NoNodeAvailableException(org.elasticsearch.client.transport.NoNodeAvailableException) TransportException(org.elasticsearch.transport.TransportException) ElasticsearchTimeoutException(org.elasticsearch.ElasticsearchTimeoutException) EsRejectedExecutionException(org.elasticsearch.common.util.concurrent.EsRejectedExecutionException)

Example 48 with BulkResponse

use of org.elasticsearch.action.bulk.BulkResponse in project storm-elastic-search by hmsonline.

the class ElasticSearchState method createIndices.

public void createIndices(TridentElasticSearchMapper mapper, List<TridentTuple> tuples) {
    BulkRequestBuilder bulkRequest = client.prepareBulk();
    Set<String> existingIndex = new HashSet<String>();
    for (TridentTuple tuple : tuples) {
        String indexName = mapper.mapToIndex(tuple);
        String type = mapper.mapToType(tuple);
        String key = mapper.mapToKey(tuple);
        Map<String, Object> data = mapper.mapToData(tuple);
        String parentId = mapper.mapToParentId(tuple);
        if (!existingIndex.contains(indexName) && !client.admin().indices().exists(new IndicesExistsRequest(indexName)).actionGet().isExists()) {
            createIndex(bulkRequest, indexName, mapper.mapToIndexSettings(tuple));
            createMapping(bulkRequest, indexName, type, mapper.mapToMappingSettings(tuple));
            existingIndex.add(indexName);
        }
        if (StringUtils.isBlank(parentId)) {
            bulkRequest.add(client.prepareIndex(indexName, type, key).setSource(data));
        } else {
            LOGGER.debug("parent: " + parentId);
            bulkRequest.add(client.prepareIndex(indexName, type, key).setSource(data).setParent(parentId));
        }
    }
    try {
        BulkResponse bulkResponse = bulkRequest.execute().actionGet();
        if (bulkResponse.hasFailures()) {
            // Index failed. Retry!
            throw new FailedException("Cannot create index via ES: " + bulkResponse.buildFailureMessage());
        }
    } catch (ElasticSearchException e) {
        StormElasticSearchUtils.handleElasticSearchException(getClass(), e);
    }
}
Also used : FailedException(backtype.storm.topology.FailedException) BulkResponse(org.elasticsearch.action.bulk.BulkResponse) BulkRequestBuilder(org.elasticsearch.action.bulk.BulkRequestBuilder) IndicesExistsRequest(org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest) ElasticSearchException(org.elasticsearch.ElasticSearchException) HashSet(java.util.HashSet) TridentTuple(storm.trident.tuple.TridentTuple)

Example 49 with BulkResponse

use of org.elasticsearch.action.bulk.BulkResponse in project metron by apache.

the class ElasticsearchBulkDocumentWriterTest method setupElasticsearchToFail.

private void setupElasticsearchToFail() throws IOException {
    final String errorMessage = "error message";
    final Exception cause = new Exception("test exception");
    final boolean isFailed = true;
    final int itemID = 0;
    // define the item failure
    BulkItemResponse.Failure failure = mock(BulkItemResponse.Failure.class);
    when(failure.getCause()).thenReturn(cause);
    when(failure.getMessage()).thenReturn(errorMessage);
    // define the item level response
    BulkItemResponse itemResponse = mock(BulkItemResponse.class);
    when(itemResponse.isFailed()).thenReturn(isFailed);
    when(itemResponse.getItemId()).thenReturn(itemID);
    when(itemResponse.getFailure()).thenReturn(failure);
    when(itemResponse.getFailureMessage()).thenReturn("error message");
    List<BulkItemResponse> itemsResponses = Collections.singletonList(itemResponse);
    // define the bulk response to indicate failure
    BulkResponse response = mock(BulkResponse.class);
    when(response.iterator()).thenReturn(itemsResponses.iterator());
    when(response.hasFailures()).thenReturn(isFailed);
    // have the client return the mock response
    when(highLevelClient.bulk(any(BulkRequest.class))).thenReturn(response);
}
Also used : BulkRequest(org.elasticsearch.action.bulk.BulkRequest) BulkItemResponse(org.elasticsearch.action.bulk.BulkItemResponse) BulkResponse(org.elasticsearch.action.bulk.BulkResponse) IOException(java.io.IOException)

Example 50 with BulkResponse

use of org.elasticsearch.action.bulk.BulkResponse in project xmall by Exrick.

the class SearchItemServiceImpl method importAllItems.

@Override
public int importAllItems() {
    try {
        Settings settings = Settings.builder().put("cluster.name", ES_CLUSTER_NAME).build();
        TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(new TransportAddress(InetAddress.getByName(ES_CONNECT_IP), 9300));
        // 批量添加
        BulkRequestBuilder bulkRequest = client.prepareBulk();
        // 查询商品列表
        List<SearchItem> itemList = itemMapper.getItemList();
        // 遍历商品列表
        for (SearchItem searchItem : itemList) {
            String image = searchItem.getProductImageBig();
            if (image != null && !"".equals(image)) {
                String[] strings = image.split(",");
                image = strings[0];
            } else {
                image = "";
            }
            searchItem.setProductImageBig(image);
            bulkRequest.add(client.prepareIndex(ITEM_INDEX, ITEM_TYPE, String.valueOf(searchItem.getProductId())).setSource(jsonBuilder().startObject().field("productId", searchItem.getProductId()).field("salePrice", searchItem.getSalePrice()).field("productName", searchItem.getProductName()).field("subTitle", searchItem.getSubTitle()).field("productImageBig", searchItem.getProductImageBig()).field("categoryName", searchItem.getCategoryName()).field("cid", searchItem.getCid()).endObject()));
        }
        BulkResponse bulkResponse = bulkRequest.get();
        log.info("更新索引成功");
        client.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new XmallException("导入ES索引库出错,请再次尝试");
    }
    return 1;
}
Also used : TransportClient(org.elasticsearch.client.transport.TransportClient) PreBuiltTransportClient(org.elasticsearch.transport.client.PreBuiltTransportClient) PreBuiltTransportClient(org.elasticsearch.transport.client.PreBuiltTransportClient) TransportAddress(org.elasticsearch.common.transport.TransportAddress) BulkResponse(org.elasticsearch.action.bulk.BulkResponse) BulkRequestBuilder(org.elasticsearch.action.bulk.BulkRequestBuilder) XmallException(cn.exrick.common.exception.XmallException) Settings(org.elasticsearch.common.settings.Settings) XmallException(cn.exrick.common.exception.XmallException) SearchItem(cn.exrick.manager.dto.front.SearchItem)

Aggregations

BulkResponse (org.elasticsearch.action.bulk.BulkResponse)108 BulkRequestBuilder (org.elasticsearch.action.bulk.BulkRequestBuilder)59 BulkItemResponse (org.elasticsearch.action.bulk.BulkItemResponse)40 BulkRequest (org.elasticsearch.action.bulk.BulkRequest)26 IOException (java.io.IOException)20 IndexRequest (org.elasticsearch.action.index.IndexRequest)19 XContentBuilder (org.elasticsearch.common.xcontent.XContentBuilder)17 IndexRequestBuilder (org.elasticsearch.action.index.IndexRequestBuilder)15 ArrayList (java.util.ArrayList)13 List (java.util.List)11 Map (java.util.Map)11 IndexResponse (org.elasticsearch.action.index.IndexResponse)10 Test (org.junit.Test)10 SearchResponse (org.elasticsearch.action.search.SearchResponse)9 SearchHit (org.elasticsearch.search.SearchHit)9 ElasticsearchException (org.elasticsearch.ElasticsearchException)8 ElasticsearchTimeoutException (org.elasticsearch.ElasticsearchTimeoutException)8 BulkProcessor (org.elasticsearch.action.bulk.BulkProcessor)8 EsRejectedExecutionException (org.elasticsearch.common.util.concurrent.EsRejectedExecutionException)8 DeleteRequest (org.elasticsearch.action.delete.DeleteRequest)7