當前位置: 首頁>>代碼示例>>Java>>正文


Java ElasticsearchException類代碼示例

本文整理匯總了Java中org.elasticsearch.ElasticsearchException的典型用法代碼示例。如果您正苦於以下問題:Java ElasticsearchException類的具體用法?Java ElasticsearchException怎麽用?Java ElasticsearchException使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


ElasticsearchException類屬於org.elasticsearch包,在下文中一共展示了ElasticsearchException類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: prepareRequest

import org.elasticsearch.ElasticsearchException; //導入依賴的package包/類
@Override
public RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
    if (request.hasContentOrSourceParam() == false) {
        throw new ElasticsearchException("request body is required");
    }

    // Creates the search request with all required params
    SearchRequest searchRequest = new SearchRequest();
    RestSearchAction.parseSearchRequest(searchRequest, request, null);

    // Creates the search template request
    SearchTemplateRequest searchTemplateRequest;
    try (XContentParser parser = request.contentOrSourceParamParser()) {
        searchTemplateRequest = PARSER.parse(parser, new SearchTemplateRequest(), null);
    }
    searchTemplateRequest.setRequest(searchRequest);

    return channel -> client.execute(SearchTemplateAction.INSTANCE, searchTemplateRequest, new RestStatusToXContentListener<>(channel));
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:20,代碼來源:RestSearchTemplateAction.java

示例2: processDocument

import org.elasticsearch.ElasticsearchException; //導入依賴的package包/類
@Override
public void processDocument(String inputText, IngestDocument ingestDocument) throws Exception {
    // call /name-translation endpoint and set the result in the field
    NameTranslationRequest request = new NameTranslationRequest.Builder(inputText, targetLanguage)
            .entityType(entityType)
            .targetScript(targetScript)
            .sourceLanguageOfUse(sourceLanguage)
            .sourceLanguageOfOrigin(sourceOrigin)
            .sourceScript(sourceScript).build();

    NameTranslationResponse response;
    try {
        // RosApi client binding's Jackson needs elevated privilege
        response = AccessController.doPrivileged((PrivilegedAction<NameTranslationResponse>) () ->
                rosAPI.getHttpRosetteAPI().perform(AbstractRosetteAPI.NAME_TRANSLATION_SERVICE_PATH, request, NameTranslationResponse.class)
        );
    } catch (HttpRosetteAPIException ex) {
        LOGGER.error(ex.getErrorResponse().getMessage());
        throw new ElasticsearchException(ex.getErrorResponse().getMessage(), ex);
    }

    ingestDocument.setFieldValue(targetField, response.getTranslation());
}
 
開發者ID:rosette-api,項目名稱:rosette-elasticsearch-plugin,代碼行數:24,代碼來源:NameTranslationProcessor.java

示例3: tokenStream

import org.elasticsearch.ElasticsearchException; //導入依賴的package包/類
@Override
public TokenStream tokenStream(Analyzer analyzer, TokenStream previous) {
    try {
        allEntries.reset(); // reset the all entries, just in case it was read already
        if (allEntries.customBoost() && fieldType().indexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0) {
            // TODO: we should be able to reuse "previous" if its instanceof AllTokenStream?
            // but we need to be careful this optimization is safe (and tested)...
            
            // AllTokenStream maps boost to 4-byte payloads, so we only need to use it any field had non-default (!= 1.0f) boost and if
            // positions are indexed:
            return AllTokenStream.allTokenStream(name, allEntries, analyzer);
        } else {
            return analyzer.tokenStream(name, allEntries);
        }
    } catch (IOException e) {
        throw new ElasticsearchException("Failed to create token stream");
    }
}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:19,代碼來源:AllField.java

示例4: RosetteApiWrapper

import org.elasticsearch.ElasticsearchException; //導入依賴的package包/類
RosetteApiWrapper(String apiKey, String altUrl) {
    if (Strings.isNullOrEmpty(apiKey)) {
        apiKey = System.getenv("ROSETTE_API_KEY");
    }

    if (Strings.isNullOrEmpty(altUrl)) {
        altUrl = System.getenv("ROSETTE_API_URL");
    }

    if ((HttpRosetteAPI.DEFAULT_URL_BASE.equalsIgnoreCase(altUrl) || Strings.isNullOrEmpty(altUrl)) && Strings.isNullOrEmpty(apiKey)) {
        throw new ElasticsearchException("Rosette plugin requires setting an API Key either via the '" + RosetteTextAnalysisPlugin.ROSETTE_API_KEY.getKey() + "' setting, or the 'ROSETTE_API_KEY' environment variable.");
    }

    HttpRosetteAPI.Builder clientBuilder = new HttpRosetteAPI.Builder();
    clientBuilder.key(apiKey).additionalHeader("X-RosetteAPI-App", APP_HEADER);
    if (!Strings.isNullOrEmpty(altUrl)) {
        LOGGER.info("Using alternative URL for Rosette API at : " + altUrl);
        clientBuilder.url(altUrl);
    }
    httpRosetteAPI = clientBuilder.build();
}
 
開發者ID:rosette-api,項目名稱:rosette-elasticsearch-plugin,代碼行數:22,代碼來源:RosetteApiWrapper.java

示例5: nodeOperation

import org.elasticsearch.ElasticsearchException; //導入依賴的package包/類
@Override
protected NodeStoreFilesMetaData nodeOperation(NodeRequest request) {
    if (request.unallocated) {
        IndexService indexService = indicesService.indexService(request.shardId.index().name());
        if (indexService == null) {
            return new NodeStoreFilesMetaData(clusterService.localNode(), null);
        }
        if (!indexService.hasShard(request.shardId.id())) {
            return new NodeStoreFilesMetaData(clusterService.localNode(), null);
        }
    }
    IndexMetaData metaData = clusterService.state().metaData().index(request.shardId.index().name());
    if (metaData == null) {
        return new NodeStoreFilesMetaData(clusterService.localNode(), null);
    }
    try {
        return new NodeStoreFilesMetaData(clusterService.localNode(), listStoreMetaData(request.shardId));
    } catch (IOException e) {
        throw new ElasticsearchException("Failed to list store metadata for shard [" + request.shardId + "]", e);
    }
}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:22,代碼來源:TransportNodesListShardStoreMetaData.java

示例6: testSingleValuedFieldOrderedByMultiValuedSubAggregationWithoutMetric

import org.elasticsearch.ElasticsearchException; //導入依賴的package包/類
public void testSingleValuedFieldOrderedByMultiValuedSubAggregationWithoutMetric() throws Exception {
    for (String index : Arrays.asList("idx", "idx_unmapped")) {
        try {
            client().prepareSearch(index)
                    .setTypes("type")
                    .addAggregation(
                            terms("terms").executionHint(randomExecutionHint()).field(SINGLE_VALUED_FIELD_NAME)
                                    .collectMode(randomFrom(SubAggCollectionMode.values()))
                                    .order(Terms.Order.aggregation("stats", true)).subAggregation(stats("stats").field("i"))).execute()
                    .actionGet();

            fail("Expected search to fail when trying to sort terms aggregation by multi-valued sug-aggregation "
                    + "where the metric name is not specified");

        } catch (ElasticsearchException e) {
            // expected
        }
    }
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:20,代碼來源:StringTermsIT.java

示例7: flush

import org.elasticsearch.ElasticsearchException; //導入依賴的package包/類
public Engine.CommitId flush(FlushRequest request) throws ElasticsearchException {
    boolean waitIfOngoing = request.waitIfOngoing();
    boolean force = request.force();
    if (logger.isTraceEnabled()) {
        logger.trace("flush with {}", request);
    }
    // we allows flush while recovering, since we allow for operations to happen
    // while recovering, and we want to keep the translog at bay (up to deletes, which
    // we don't gc).
    verifyStartedOrRecovering();

    long time = System.nanoTime();
    Engine.CommitId commitId = engine().flush(force, waitIfOngoing);
    flushMetric.inc(System.nanoTime() - time);
    return commitId;

}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:18,代碼來源:IndexShard.java

示例8: nodeSettings

import org.elasticsearch.ElasticsearchException; //導入依賴的package包/類
@Override
public Settings nodeSettings(int nodeOrdinal) {
    Settings.Builder builder = Settings.builder().put(NodeEnvironment.MAX_LOCAL_STORAGE_NODES_SETTING.getKey(), numOfNodes);

    String[] unicastHosts = new String[unicastHostOrdinals.length];
    if (nodeOrdinal >= unicastHostPorts.length) {
        throw new ElasticsearchException("nodeOrdinal [" + nodeOrdinal + "] is greater than the number unicast ports [" + unicastHostPorts.length + "]");
    } else {
        // we need to pin the node port & host so we'd know where to point things
        builder.put(TransportSettings.PORT.getKey(), unicastHostPorts[nodeOrdinal]);
        builder.put(TransportSettings.HOST.getKey(), IP_ADDR); // only bind on one IF we use v4 here by default
        builder.put(NetworkModule.HTTP_ENABLED.getKey(), false);
        for (int i = 0; i < unicastHostOrdinals.length; i++) {
            unicastHosts[i] = IP_ADDR + ":" + (unicastHostPorts[unicastHostOrdinals[i]]);
        }
    }
    builder.putArray("discovery.zen.ping.unicast.hosts", unicastHosts);
    return builder.put(super.nodeSettings(nodeOrdinal)).build();
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:20,代碼來源:ClusterDiscoveryConfiguration.java

示例9: updateMinMasterNodes

import org.elasticsearch.ElasticsearchException; //導入依賴的package包/類
/**
 * updates the min master nodes setting in the current running cluster.
 *
 * @param eligibleMasterNodeCount the number of master eligible nodes to use as basis for the min master node setting
 */
private int updateMinMasterNodes(int eligibleMasterNodeCount) {
    assert autoManageMinMasterNodes;
    final int minMasterNodes = getMinMasterNodes(eligibleMasterNodeCount);
    if (getMasterNodesCount() > 0) {
        // there should be at least one master to update
        logger.debug("updating min_master_nodes to [{}]", minMasterNodes);
        try {
            assertAcked(client().admin().cluster().prepareUpdateSettings().setTransientSettings(
                Settings.builder().put(DISCOVERY_ZEN_MINIMUM_MASTER_NODES_SETTING.getKey(), minMasterNodes)
            ));
        } catch (Exception e) {
            throw new ElasticsearchException("failed to update minimum master node to [{}] (current masters [{}])", e,
                minMasterNodes, getMasterNodesCount());
        }
    }
    return minMasterNodes;
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:23,代碼來源:InternalTestCluster.java

示例10: getKeys

import org.elasticsearch.ElasticsearchException; //導入依賴的package包/類
@Override
protected NumericDocValues getKeys(LeafReaderContext context) {
    try {
        values = valuesSource.longValues(context);
    } catch (IOException e) {
        throw new ElasticsearchException("Error reading values", e);
    }
    return new NumericDocValues() {
        @Override
        public long get(int doc) {
            values.setDocument(doc);
            final int valuesCount = values.count();
            if (valuesCount > 1) {
                throw new IllegalArgumentException("Sample diversifying key must be a single valued-field");
            }
            if (valuesCount == 1) {
                return values.valueAt(0);
            }
            return Long.MIN_VALUE;
        }
    };
}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:23,代碼來源:DiversifiedNumericSamplerAggregator.java

示例11: recoveryFromSnapshot

import org.elasticsearch.ElasticsearchException; //導入依賴的package包/類
public int recoveryFromSnapshot(Engine engine, Translog.Snapshot snapshot) throws IOException {
    Translog.Operation operation;
    int opsRecovered = 0;
    while ((operation = snapshot.next()) != null) {
        try {
            performRecoveryOperation(engine, operation, true);
            opsRecovered++;
        } catch (ElasticsearchException e) {
            if (e.status() == RestStatus.BAD_REQUEST) {
                // mainly for MapperParsingException and Failure to detect xcontent
                logger.info("ignoring recovery of a corrupt translog entry", e);
            } else {
                throw e;
            }
        }
    }
    return opsRecovered;
}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:19,代碼來源:TranslogRecoveryPerformer.java

示例12: prepare

import org.elasticsearch.ElasticsearchException; //導入依賴的package包/類
@Override
public void prepare(PercolateContext context, ParsedDocument parsedDocument) {
    MemoryIndex memoryIndex = cache.get();
    for (IndexableField field : parsedDocument.rootDoc().getFields()) {
        if (field.fieldType().indexOptions() == IndexOptions.NONE && field.name().equals(UidFieldMapper.NAME)) {
            continue;
        }
        try {
            Analyzer analyzer = context.mapperService().documentMapper(parsedDocument.type()).mappers().indexAnalyzer();
            // TODO: instead of passing null here, we can have a CTL<Map<String,TokenStream>> and pass previous,
            // like the indexer does
            try (TokenStream tokenStream = field.tokenStream(analyzer, null)) {
                if (tokenStream != null) {
                    memoryIndex.addField(field.name(), tokenStream, field.boost());
                }
             }
        } catch (Exception e) {
            throw new ElasticsearchException("Failed to create token stream for [" + field.name() + "]", e);
        }
    }
    context.initialize(new DocEngineSearcher(memoryIndex), parsedDocument);
}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:23,代碼來源:SingleDocumentPercolatorIndex.java

示例13: getUserDictionary

import org.elasticsearch.ElasticsearchException; //導入依賴的package包/類
public static UserDictionary getUserDictionary(Environment env, Settings settings) {
    try {
        final Reader reader = Analysis.getReaderFromFile(env, settings, USER_DICT_OPTION);
        if (reader == null) {
            return null;
        } else {
            try {
                return UserDictionary.open(reader);
            } finally {
                reader.close();
            }
        }
    } catch (IOException e) {
        throw new ElasticsearchException("failed to load kuromoji user dictionary", e);
    }
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:17,代碼來源:KuromojiTokenizerFactory.java

示例14: writeOnLocal

import org.elasticsearch.ElasticsearchException; //導入依賴的package包/類
public <Request extends ActionRequest, Response extends ActionResponse> void writeOnLocal(final Request request,
        final ActionListener<Response> listener) {
    final ActionListener<Response> next = wrap(res -> {
        final short classType = RequestUtils.getClassType(request);
        if (classType > 0) {
            synchronized (this) {
                streamOutput.writeShort(classType);
                request.writeTo(streamOutput);
                if (flushPerDoc) {
                    streamOutput.flush();
                }
            }
        } else {
            throw new ElasticsearchException("Unknown request: " + request);
        }
        listener.onResponse(res);
    }, listener::onFailure);

    if (streamOutput == null || streamOutput.getByteCount() > dataFileSize) {
        createStreamOutput(next);
    } else {
        next.onResponse(null);
    }
}
 
開發者ID:codelibs,項目名稱:elasticsearch-indexing-proxy,代碼行數:25,代碼來源:IndexingProxyService.java

示例15: testSingleValuedFieldOrderedByMultiValuedSubAggregationWithUknownMetric

import org.elasticsearch.ElasticsearchException; //導入依賴的package包/類
public void testSingleValuedFieldOrderedByMultiValuedSubAggregationWithUknownMetric() throws Exception {
    for (String index : Arrays.asList("idx", "idx_unmapped")) {
        try {
            client().prepareSearch(index).setTypes("type")
                    .addAggregation(terms("terms")
                            .field(SINGLE_VALUED_FIELD_NAME)
                            .collectMode(randomFrom(SubAggCollectionMode.values()))
                            .order(Terms.Order.aggregation("stats.foo", true))
                            .subAggregation(stats("stats").field(SINGLE_VALUED_FIELD_NAME))
                    ).execute().actionGet();

            fail("Expected search to fail when trying to sort terms aggregation by multi-valued sug-aggregation " +
                    "with an unknown specified metric to order by");

        } catch (ElasticsearchException e) {
            // expected
        }
    }
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:20,代碼來源:LongTermsIT.java


注:本文中的org.elasticsearch.ElasticsearchException類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。