当前位置: 首页>>代码示例>>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: if

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;未经允许,请勿转载。