org.elasticsearch.ElasticsearchException Java Examples

The following examples show how to use org.elasticsearch.ElasticsearchException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: Elasticsearch   Author: baidu   File: TransportShardMultiTermsVectorAction.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected MultiTermVectorsShardResponse shardOperation(MultiTermVectorsShardRequest request, ShardId shardId) {
    MultiTermVectorsShardResponse response = new MultiTermVectorsShardResponse();
    for (int i = 0; i < request.locations.size(); i++) {
        TermVectorsRequest termVectorsRequest = request.requests.get(i);
        try {
            IndexService indexService = indicesService.indexServiceSafe(request.index());
            IndexShard indexShard = indexService.shardSafe(shardId.id());
            TermVectorsResponse termVectorsResponse = indexShard.termVectorsService().getTermVectors(termVectorsRequest, shardId.getIndex());
            termVectorsResponse.updateTookInMillis(termVectorsRequest.startTime());
            response.add(request.locations.get(i), termVectorsResponse);
        } catch (Throwable t) {
            if (TransportActions.isShardNotAvailableException(t)) {
                throw (ElasticsearchException) t;
            } else {
                logger.debug("{} failed to execute multi term vectors for [{}]/[{}]", t, shardId, termVectorsRequest.type(), termVectorsRequest.id());
                response.add(request.locations.get(i),
                        new MultiTermVectorsResponse.Failure(request.index(), termVectorsRequest.type(), termVectorsRequest.id(), t));
            }
        }
    }

    return response;
}
 
Example #2
Source Project: io   Author: fujitsu-pio   File: AbstractRetryableEsRequestTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * リトライ処理中の特定例外処理からContinueRetryが投げられた後、リトライ処理に移行すること.
 */
@Test
public void リトライ処理中の特定例外処理からContinueRetryが投げられた後_リトライ処理に移行すること() {
    TestRequest requestMock = Mockito.spy(new TestRequest());

    NodeDisconnectedException toBeThrown = Mockito.mock(NodeDisconnectedException.class);

    Mockito.doThrow(toBeThrown) // 初回リクエスト
            .doThrow(toBeThrown) // リトライ1回目
            .doThrow(new SettingsException("foo")) // リトライ2回目. この時は、 #onParticularError()でリトライ継続のために
                                                   // ContinueRetryが投げられる.
            .doThrow(toBeThrown) // リトライ3回目
            .doReturn(SUCCESS_RESPONSE)
            .when(requestMock)
            .doProcess();

    String result = requestMock.doRequest();
    assertEquals(SUCCESS_RESPONSE, result);
    // 初回 + リトライ3回 + 処理成功で、5回呼ばれるはず.
    Mockito.verify(requestMock, Mockito.times(5)).doProcess();
    Mockito.verify(requestMock, Mockito.times(1)).onParticularError(Mockito.any(ElasticsearchException.class));
}
 
Example #3
Source Project: Elasticsearch   Author: baidu   File: AdapterActionFuture.java    License: Apache License 2.0 6 votes vote down vote up
static RuntimeException rethrowExecutionException(ExecutionException e) {
    if (e.getCause() instanceof ElasticsearchException) {
        ElasticsearchException esEx = (ElasticsearchException) e.getCause();
        Throwable root = esEx.unwrapCause();
        if (root instanceof ElasticsearchException) {
            return (ElasticsearchException) root;
        } else if (root instanceof RuntimeException) {
            return (RuntimeException) root;
        }
        return new UncategorizedExecutionException("Failed execution", root);
    } else if (e.getCause() instanceof RuntimeException) {
        return (RuntimeException) e.getCause();
    } else {
        return new UncategorizedExecutionException("Failed execution", e);
    }
}
 
Example #4
Source Project: io   Author: fujitsu-pio   File: AbstractRetryableEsRequestTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * NoNodeAvailableExceptionが続き, リトライ3回目で成功した場合、適切な復帰値が返ること.
 */
@Test
public void NoNodeAvailableExceptionが続き_リトライ3回目で成功した場合_適切な復帰値が返ること() {

    TestRequest requestMock = Mockito.spy(new TestRequest());

    NoNodeAvailableException toBeThrown = Mockito.mock(NoNodeAvailableException.class);
    Mockito.doThrow(toBeThrown) // 初回
            .doThrow(toBeThrown) // リトライ1回目
            .doThrow(toBeThrown) // リトライ2回目
            .doReturn(SUCCESS_RESPONSE) // リトライ3回目で正常復帰
            .when(requestMock)
            .doProcess();

    String result = requestMock.doRequest();
    assertEquals(SUCCESS_RESPONSE, result);
    // doProcessが4回呼び出されるはず
    Mockito.verify(requestMock, Mockito.times(4)).doProcess();
    Mockito.verify(requestMock, Mockito.times(0)).onParticularError(Mockito.any(ElasticsearchException.class));
}
 
Example #5
Source Project: io   Author: fujitsu-pio   File: AbstractRetryableEsRequestTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 初回リクエスト時に特定例外が発生した場合、特定例外用処理が呼び出されてレスポンスが返ること.
 */
@Test
public void 初回リクエスト時に特定例外が発生した場合_特定例外用処理が呼び出されてレスポンスが返ること() {

    TestRequest requestMock = Mockito.spy(new TestRequest());

    EsExceptionForTest toBeThrown = Mockito.mock(EsExceptionForTest.class);
    Mockito.doThrow(toBeThrown) // 初回
            .when(requestMock)
            .doProcess();

    String result = requestMock.doRequest();
    assertEquals(ON_ERROR_RESPONSE, result);
    Mockito.verify(requestMock, Mockito.times(1)).doProcess();
    Mockito.verify(requestMock, Mockito.times(1)).onParticularError(Mockito.any(ElasticsearchException.class));
}
 
Example #6
Source Project: act-platform   Author: mnemonic-no   File: FactSearchManager.java    License: ISC License 6 votes vote down vote up
private ScrollingSearchResult.ScrollingBatch<FactDocument> fetchNextFactsBatch(String scrollId) {
  SearchResponse response;
  try {
    SearchScrollRequest request = new SearchScrollRequest()
            .scrollId(scrollId)
            .scroll(searchScrollExpiration);
    response = clientFactory.getClient().scroll(request, RequestOptions.DEFAULT);
  } catch (ElasticsearchException | IOException ex) {
    LOGGER.warning(ex, "Could not perform request to retrieve next batch of search results. Stop scrolling.");
    return ScrollingSearchResult.emptyBatch();
  }

  if (response.status() != RestStatus.OK) {
    LOGGER.warning("Could not retrieve next batch of search results (response code %s). Stop scrolling.", response.status());
    return ScrollingSearchResult.emptyBatch();
  }

  return createFactsBatch(response);
}
 
Example #7
Source Project: io   Author: fujitsu-pio   File: AbstractRetryableEsRequestTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 初回リクエストでリトライ対象外の例外が発生した場合、リトライせずに初回例外を投げること.
 */
@Test(expected = EsClientException.class)
public void 初回リクエストでリトライ対象外の例外が発生した場合_リトライせずに初回例外を投げること() {
    TestRequest requestMock = Mockito.spy(new TestRequest());

    Mockito.doThrow(new IndexMissingException(new Index("abc"))) // なぜかモック例外だとうまく動かなかった.
            .when(requestMock)
            .doProcess();

    try {
        requestMock.doRequest();
        fail("Should not return");
    } finally {
        Mockito.verify(requestMock, Mockito.times(1)).doProcess();
        Mockito.verify(requestMock, Mockito.times(0)).onParticularError(Mockito.any(ElasticsearchException.class));
    }
}
 
Example #8
@Override
public ElasticsearchSecurityException exceptionProcessingRequest(final TransportMessage message, final Exception e) {
    final ElasticsearchSecurityException se = super.exceptionProcessingRequest(message, e);
    String outToken = "";

    if (e instanceof ElasticsearchException) {
        final ElasticsearchException kae = (ElasticsearchException) e;
        if (kae.getHeader("kerberos_out_token") != null) {
            outToken = " " + kae.getHeader("kerberos_out_token").get(0);
        }
    }
    se.addHeader(KrbConstants.WWW_AUTHENTICATE, KrbConstants.NEGOTIATE + outToken);

    if (logger.isDebugEnabled()) {
        logger.debug("exception for transport message: {}", e.toString());
    }

    return se;
}
 
Example #9
Source Project: elasticsearch-helper   Author: jprante   File: IngestReplicaShardRequest.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void writeTo(StreamOutput out) throws IOException {
    super.writeTo(out);
    out.writeString(index);
    timeout.writeTo(out);
    out.writeLong(ingestId);
    shardId.writeTo(out);
    out.writeVInt(actionRequests.size());
    for (ActionRequest<?> actionRequest : actionRequests) {
        if (actionRequest == null) {
            out.writeBoolean(false);
            continue;
        }
        out.writeBoolean(true);
        if (actionRequest instanceof IndexRequest) {
            out.writeBoolean(true);
        } else if (actionRequest instanceof DeleteRequest) {
            out.writeBoolean(false);
        } else {
            throw new ElasticsearchException("action request not supported: " + actionRequest.getClass().getName());
        }
        actionRequest.writeTo(out);
    }
}
 
Example #10
Source Project: vind   Author: RBMHTechnology   File: ElasticSearchServer.java    License: Apache License 2.0 6 votes vote down vote up
private IndexResult indexMultipleDocuments(List<Document> docs, int withinMs) {
    log.warn("Parameter 'within' not in use in elastic search backend");
    final StopWatch elapsedTime = StopWatch.createStarted();
    final List<Map<String,Object>> jsonDocs = docs.parallelStream()
            .map(DocumentUtil::createInputDocument)
            .collect(Collectors.toList());
    try {
        if (elasticClientLogger.isTraceEnabled()) {
            elasticClientLogger.debug(">>> add({})", jsonDocs);
        } else {
            elasticClientLogger.debug(">>> add({})", jsonDocs);
        }

        final BulkResponse response =this.elasticSearchClient.add(jsonDocs) ;
        elapsedTime.stop();
        return new IndexResult(elapsedTime.getTime()).setElapsedTime(elapsedTime.getTime());

    } catch (ElasticsearchException | IOException e) {
        log.error("Cannot index documents {}", jsonDocs, e);
        throw new SearchServerException("Cannot index documents", e);
    }
}
 
Example #11
Source Project: elasticsearch-helper   Author: jprante   File: IngestTransportClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public IngestTransportClient bulkDelete(org.elasticsearch.action.delete.DeleteRequest deleteRequest) {
    if (closed) {
        if (throwable != null) {
            throw new ElasticsearchException("client is closed, possible reason: ", throwable);
        } else {
            throw new ElasticsearchException("client is closed");
        }
    }
    try {
        metric.getCurrentIngest().inc(deleteRequest.index(), deleteRequest.type(), deleteRequest.id());
        ingestProcessor.add(new DeleteRequest(deleteRequest));
    } catch (Exception e) {
        logger.error("add of delete request failed: " + e.getMessage(), e);
        throwable = e;
        closed = true;
    }
    return this;
}
 
Example #12
Source Project: elasticsearch-helper   Author: jprante   File: IngestTransportClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public IngestTransportClient delete(String index, String type, String id) {
    if (closed) {
        if (throwable != null) {
            throw new ElasticsearchException("client is closed, possible reason: ", throwable);
        } else {
            throw new ElasticsearchException("client is closed");
        }
    }
    try {
        metric.getCurrentIngest().inc(index, type, id);
        ingestProcessor.add(new DeleteRequest(index).type(type).id(id));
    } catch (Exception e) {
        logger.error("add of delete request failed: " + e.getMessage(), e);
        throwable = e;
        closed = true;
    }
    return this;
}
 
Example #13
Source Project: storm-trident-elasticsearch   Author: fhussonnois   File: ESIndexState.java    License: Apache License 2.0 6 votes vote down vote up
public void bulkUpdateIndices(List<TridentTuple> inputs, TridentTupleMapper<Document<T>> mapper, BulkResponseHandler handler) {
    BulkRequestBuilder bulkRequest = client.prepareBulk();
    for (TridentTuple input : inputs) {
        Document<T> doc = mapper.map(input);
        byte[] source = serializeSourceOrFail(doc);
        IndexRequestBuilder request = client.prepareIndex(doc.getName(), doc.getType(), doc.getId()).setSource(source);

        if(doc.getParentId() != null) {
            request.setParent(doc.getParentId());
        }
        bulkRequest.add(request);
    }

    if( bulkRequest.numberOfActions() > 0) {
        try {
            handler.handle(bulkRequest.execute().actionGet());
        } catch(ElasticsearchException e) {
            LOGGER.error("error while executing bulk request to elasticsearch");
            throw new FailedException("Failed to store data into elasticsearch", e);
        }
    }
}
 
Example #14
Source Project: Elasticsearch   Author: baidu   File: IndexFieldTerm.java    License: Apache License 2.0 6 votes vote down vote up
public void setDocument(int docId) {
    assert (postings != null);
    try {
        // we try to advance to the current document.
        int currentDocPos = postings.docID();
        if (currentDocPos < docId) {
            currentDocPos = postings.advance(docId);
        }
        if (currentDocPos == docId) {
            freq = postings.freq();
        } else {
            freq = 0;
        }
        iterator.nextDoc();
    } catch (IOException e) {
        throw new ElasticsearchException("While trying to initialize term positions in IndexFieldTerm.setNextDoc() ", e);
    }
}
 
Example #15
Source Project: Elasticsearch   Author: baidu   File: TransportShardMultiPercolateAction.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Response shardOperation(Request request, ShardId shardId) {
    // TODO: Look into combining the shard req's docs into one in memory index.
    Response response = new Response();
    response.items = new ArrayList<>(request.items.size());
    for (Request.Item item : request.items) {
        Response.Item responseItem;
        int slot = item.slot;
        try {
            responseItem = new Response.Item(slot, percolatorService.percolate(item.request));
        } catch (Throwable t) {
            if (TransportActions.isShardNotAvailableException(t)) {
                throw (ElasticsearchException) t;
            } else {
                logger.debug("{} failed to multi percolate", t, request.shardId());
                responseItem = new Response.Item(slot, t);
            }
        }
        response.items.add(responseItem);
    }
    return response;
}
 
Example #16
Source Project: io   Author: fujitsu-pio   File: AbstractRetryableEsRequestTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * ClusterBlockExceptionが続き_リトライ5回目で成功した場合_適切な復帰値が返ること.
 */
@Test
public void ClusterBlockExceptionが続き_リトライ5回目で成功した場合_適切な復帰値が返ること() {

    TestRequest requestMock = Mockito.spy(new TestRequest());

    ClusterBlockException toBeThrown = Mockito.mock(ClusterBlockException.class);
    Mockito.doThrow(toBeThrown) // 初回
            .doThrow(toBeThrown) // リトライ1回目
            .doThrow(toBeThrown) // リトライ2回目
            .doThrow(toBeThrown) // リトライ3回目
            .doThrow(toBeThrown) // リトライ4回目
            .doReturn(SUCCESS_RESPONSE) // リトライ5回目で正常復帰
            .when(requestMock)
            .doProcess();

    String result = requestMock.doRequest();
    assertEquals(SUCCESS_RESPONSE, result);
    // doProcessが6回呼び出されるはず
    Mockito.verify(requestMock, Mockito.times(6)).doProcess();
    Mockito.verify(requestMock, Mockito.times(0)).onParticularError(Mockito.any(ElasticsearchException.class));
}
 
Example #17
Source Project: elasticsearch-taste   Author: codelibs   File: ElasticsearchDataModel.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void setPreference(final long userID, final long itemID,
        final float value) {
    createUserID(userID);
    createItemID(itemID);

    final Map<String, Object> source = new HashMap<>();
    source.put(userIdField, userID);
    source.put(itemIdField, itemID);
    source.put(valueField, value);
    source.put(timestampField, new Date());
    try {
        client.prepareIndex(preferenceIndex, preferenceType)
                .setSource(source).setRefresh(true).execute().actionGet();
    } catch (final ElasticsearchException e) {
        throw new TasteException("Failed to set (" + userID + "," + itemID
                + "," + value + ")", e);
    }
}
 
Example #18
Source Project: logstash   Author: mesos   File: ElasticsearchContainer.java    License: Apache License 2.0 6 votes vote down vote up
public Client createClient() {
    final AtomicReference<Client> elasticsearchClient = new AtomicReference<>();
    await().atMost(30, TimeUnit.SECONDS).pollDelay(1, TimeUnit.SECONDS).until(() -> {
        Client c = new TransportClient(ImmutableSettings.settingsBuilder().put("cluster.name", elasticsearchClusterName).build()).addTransportAddress(new InetSocketTransportAddress(getIpAddress(), 9300));
        try {
            c.admin().cluster().health(Requests.clusterHealthRequest("_all")).actionGet();
        } catch (ElasticsearchException e) {
            c.close();
            return false;
        }
        elasticsearchClient.set(c);
        return true;
    });
    assertEquals(elasticsearchClusterName, elasticsearchClient.get().admin().cluster().health(Requests.clusterHealthRequest("_all")).actionGet().getClusterName());
    return elasticsearchClient.get();
}
 
Example #19
Source Project: trident-elasticsearch   Author: hmsonline   File: IndexState.java    License: Apache License 2.0 6 votes vote down vote up
private void runBulk(BulkRequestBuilder bulkRequest) {
    if(bulkRequest.numberOfActions() > 0) {
        int tryCount = 0;
        boolean shouldTryAgain;
        do {
            shouldTryAgain = false;
            try {                
                BulkResponse bulkResponse = bulkRequest.execute().actionGet();
                if (bulkResponse.hasFailures()) {
                    shouldTryAgain = this.exceptionHandler.onBulkRequestFailure(bulkResponse, tryCount);
                    tryCount++;
                }
            } catch (ElasticsearchException e) {
                shouldTryAgain = this.exceptionHandler.onElasticSearchException(e, tryCount);
                tryCount++;
            }
        } while (shouldTryAgain);
    } else {
        LOG.debug("Empty batch being submitted");
    }
}
 
Example #20
Source Project: io   Author: fujitsu-pio   File: AbstractRetryableEsRequestTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 初回リクエストでリトライ対象外の例外が発生した場合、リトライせずに初回例外を投げること.
 */
@Test(expected = EsClientException.class)
public void 初回リクエストでリトライ対象外の例外が発生した場合_リトライせずに初回例外を投げること() {
    TestRequest requestMock = Mockito.spy(new TestRequest());

    Mockito.doThrow(new IndexNotFoundException("abc")) // なぜかモック例外だとうまく動かなかった.
            .when(requestMock)
            .doProcess();

    try {
        requestMock.doRequest();
        fail("Should not return");
    } finally {
        Mockito.verify(requestMock, Mockito.times(1)).doProcess();
        Mockito.verify(requestMock, Mockito.times(0)).onParticularError(Mockito.any(ElasticsearchException.class));
    }
}
 
Example #21
Source Project: Elasticsearch   Author: baidu   File: SyncedFlushService.java    License: Apache License 2.0 6 votes vote down vote up
private ShardSyncedFlushResponse performSyncedFlush(ShardSyncedFlushRequest request) {
    IndexService indexService = indicesService.indexServiceSafe(request.shardId().getIndex());
    IndexShard indexShard = indexService.shardSafe(request.shardId().id());
    logger.trace("{} performing sync flush. sync id [{}], expected commit id {}", request.shardId(), request.syncId(), request.expectedCommitId());
    Engine.SyncedFlushResult result = indexShard.syncFlush(request.syncId(), request.expectedCommitId());
    logger.trace("{} sync flush done. sync id [{}], result [{}]", request.shardId(), request.syncId(), result);
    switch (result) {
        case SUCCESS:
            return new ShardSyncedFlushResponse();
        case COMMIT_MISMATCH:
            return new ShardSyncedFlushResponse("commit has changed");
        case PENDING_OPERATIONS:
            return new ShardSyncedFlushResponse("pending operations");
        default:
            throw new ElasticsearchException("unknown synced flush result [" + result + "]");
    }
}
 
Example #22
Source Project: io   Author: fujitsu-pio   File: AbstractRetryableEsRequestTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 初回リクエストでNoNodeAvailableException、リトライ1回目で成功した場合、適切な復帰値が返ること.
 */
@Test
public void 初回リクエストでNoNodeAvailableException_リトライ1回目で成功した場合_適切な復帰値が返ること() {

    TestRequest requestMock = Mockito.spy(new TestRequest());

    NoNodeAvailableException toBeThrown = Mockito.mock(NoNodeAvailableException.class);
    Mockito.doThrow(toBeThrown)
            .doReturn(SUCCESS_RESPONSE)
            .when(requestMock)
            .doProcess();

    String result = requestMock.doRequest();
    assertEquals(SUCCESS_RESPONSE, result);
    Mockito.verify(requestMock, Mockito.times(2)).doProcess();
    Mockito.verify(requestMock, Mockito.times(0)).onParticularError(Mockito.any(ElasticsearchException.class));
}
 
Example #23
Source Project: elasticsearch-gatherer   Author: jprante   File: GathererService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doStart() throws ElasticSearchException {

    // announce default gatherers
    announceGatherers();

    // the load updater task
    ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(daemonThreadFactory(settings, "gatherer_load_watcher"));
    executorService.scheduleAtFixedRate(new Thread() {
        public void run() {
            double load = operatingSystemMXBean.getSystemLoadAverage();
            nodeService.putAttribute(GathererConstants.GATHERER_LOAD, Double.toString(load));
        }
    }, 1L, 1L, TimeUnit.MINUTES);

    // the queue length updater task
    executorService.scheduleAtFixedRate(new Thread() {
        public void run() {
            int length = 0; // TODO getPendingJobs();
            nodeService.putAttribute(GathererConstants.GATHERER_LENGTH, Integer.toString(length));
        }
    }, 1L, 5L, TimeUnit.SECONDS);

    logger.info("started");
}
 
Example #24
Source Project: elasticsearch-inout-plugin   Author: crate   File: FieldWriter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Method to recursively create a nested object
 */
private void writeMap(Map<String, Object> root, Object value, String part) {
    if (part.contains(".")) {
        String[] parts = part.split("\\.", 2);
        Object o = root.get(parts[0]);
        if (o == null) {
            o = new HashMap<String, Object>();
        } else if (!(o instanceof Map)) {
            throw new ElasticSearchException("Error on rewriting objects: Mixed objects and values");
        }
        Map<String, Object> sub = (Map<String, Object>) o;
        writeMap(sub, value, parts[1]);
        root.put(parts[0], sub);
    } else {
        if (((Map<String, Object>) root).get(part) instanceof Map) {
            throw new ElasticSearchException("Error on rewriting objects: Mixed objects and values");
        }
        root.put(part, value);
    }
}
 
Example #25
Source Project: Elasticsearch   Author: baidu   File: BestDocsDeferringCollector.java    License: Apache License 2.0 5 votes vote down vote up
public PerParentBucketSamples(long parentBucket, Scorer scorer, LeafReaderContext readerContext) {
    try {
        this.parentBucket = parentBucket;
        tdc = createTopDocsCollector(shardSize);
        currentLeafCollector = tdc.getLeafCollector(readerContext);
        setScorer(scorer);
    } catch (IOException e) {
        throw new ElasticsearchException("IO error creating collector", e);
    }
}
 
Example #26
Source Project: Elasticsearch   Author: baidu   File: TransportAnalyzeAction.java    License: Apache License 2.0 5 votes vote down vote up
private static List<AnalyzeResponse.AnalyzeToken> simpleAnalyze(AnalyzeRequest request, Analyzer analyzer, String field) {
    List<AnalyzeResponse.AnalyzeToken> tokens = new ArrayList<>();
    int lastPosition = -1;
    int lastOffset = 0;
    for (String text : request.text()) {
        try (TokenStream stream = analyzer.tokenStream(field, text)) {
            stream.reset();
            CharTermAttribute term = stream.addAttribute(CharTermAttribute.class);
            PositionIncrementAttribute posIncr = stream.addAttribute(PositionIncrementAttribute.class);
            OffsetAttribute offset = stream.addAttribute(OffsetAttribute.class);
            TypeAttribute type = stream.addAttribute(TypeAttribute.class);

            while (stream.incrementToken()) {
                int increment = posIncr.getPositionIncrement();
                if (increment > 0) {
                    lastPosition = lastPosition + increment;
                }
                tokens.add(new AnalyzeResponse.AnalyzeToken(term.toString(), lastPosition, lastOffset + offset.startOffset(), lastOffset + offset.endOffset(), type.type(), null));

            }
            stream.end();
            lastOffset += offset.endOffset();
            lastPosition += posIncr.getPositionIncrement();

            lastPosition += analyzer.getPositionIncrementGap(field);
            lastOffset += analyzer.getOffsetGap(field);
        } catch (IOException e) {
            throw new ElasticsearchException("failed to analyze", e);
        }
    }
    return tokens;
}
 
Example #27
Source Project: io   Author: fujitsu-pio   File: EsIndexImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
SearchResponse onParticularError(ElasticsearchException e) {
    if (e instanceof IndexMissingException || e.getCause() instanceof IndexMissingException) {
        return null;
    }
    if (e instanceof SearchPhaseExecutionException) {
        throw new EsClientException("unknown property was appointed.", e);
    }
    throw e;
}
 
Example #28
Source Project: crate   Author: crate   File: UnsafeBootstrapMasterCommand.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected boolean validateBeforeLock(Terminal terminal, Environment env) {
    Settings settings = env.settings();
    terminal.println(Terminal.Verbosity.VERBOSE, "Checking node.master setting");
    Boolean master = Node.NODE_MASTER_SETTING.get(settings);
    if (master == false) {
        throw new ElasticsearchException(NOT_MASTER_NODE_MSG);
    }

    return true;
}
 
Example #29
Source Project: Elasticsearch   Author: baidu   File: BytesRestResponse.java    License: Apache License 2.0 5 votes vote down vote up
public BytesRestResponse(RestChannel channel, RestStatus status, Throwable t) throws IOException {
    this.status = status;
    if (channel.request().method() == RestRequest.Method.HEAD) {
        this.content = BytesArray.EMPTY;
        this.contentType = TEXT_CONTENT_TYPE;
    } else {
        XContentBuilder builder = convert(channel, status, t);
        this.content = builder.bytes();
        this.contentType = builder.contentType().restContentType();
    }
    if (t instanceof ElasticsearchException) {
        copyHeaders(((ElasticsearchException) t));
    }
}
 
Example #30
Source Project: elasticsearch-helper   Author: jprante   File: BulkTransportClient.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public BulkTransportClient deleteIndex(String index) {
    if (closed) {
        throw new ElasticsearchException("client is closed");
    }
    super.deleteIndex(index);
    return this;
}