Java Code Examples for org.elasticsearch.action.search.SearchResponse#getSuccessfulShards()

The following examples show how to use org.elasticsearch.action.search.SearchResponse#getSuccessfulShards() . 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 File: DefaultRequestHandler.java    From elasticsearch-taste with Apache License 2.0 6 votes vote down vote up
protected void validateRespose(final SearchResponse response) {
    final int totalShards = response.getTotalShards();
    final int successfulShards = response.getSuccessfulShards();
    if (totalShards != successfulShards) {
        throw new MissingShardsException(totalShards - successfulShards
                + " shards are failed.");
    }
    final ShardSearchFailure[] failures = response.getShardFailures();
    if (failures.length > 0) {
        final StringBuilder buf = new StringBuilder();
        for (final ShardOperationFailedException failure : failures) {
            buf.append('\n').append(failure.toString());
        }
        throw new OperationFailedException("Search Operation Failed: "
                + buf.toString());
    }
}
 
Example 2
Source File: QueryActionElasticExecutor.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
public static SearchResponse executeSearchAction(DefaultQueryAction searchQueryAction) throws SqlParseException {
    SqlElasticSearchRequestBuilder builder  =  searchQueryAction.explain();
    SearchResponse resp = (SearchResponse) builder.get();

    //
    if (resp.getFailedShards() > 0) {
        if (resp.getSuccessfulShards() < 1) {
            throw new IllegalStateException("fail to search[" + builder + "], " + Arrays.toString(resp.getShardFailures()));
        }

        LOGGER.warn("The failures that occurred during the search[{}]: {}", builder, Arrays.toString(resp.getShardFailures()));
    }

    return resp;
}
 
Example 3
Source File: QueryActionElasticExecutor.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
public static Aggregations executeAggregationAction(AggregationQueryAction aggregationQueryAction) throws SqlParseException {
    SqlElasticSearchRequestBuilder select =  aggregationQueryAction.explain();
    SearchResponse resp = (SearchResponse) select.get();

    //
    if (resp.getFailedShards() > 0) {
        if (resp.getSuccessfulShards() < 1) {
            throw new IllegalStateException("fail to aggregation[" + select + "], " + Arrays.toString(resp.getShardFailures()));
        }

        LOGGER.warn("The failures that occurred during the aggregation[{}]: {}", select, Arrays.toString(resp.getShardFailures()));
    }

    return resp.getAggregations();
}
 
Example 4
Source File: Select.java    From code with Apache License 2.0 4 votes vote down vote up
public void after() throws IOException {
    //3.获取查询结果
    SearchResponse searchResponse = restHighLevelClient.search(searchRequest,
            RequestOptions.DEFAULT);

    // 查询花费时间,单位是毫秒
    TimeValue took = searchResponse.getTook();
    // 分片信息
    int total = searchResponse.getTotalShards();
    int success = searchResponse.getSuccessfulShards();
    int skipped = searchResponse.getSkippedShards();
    int failed = searchResponse.getFailedShards();
    // 搜索结果总览对象
    SearchHits searchHits = searchResponse.getHits();
    // 搜索到的总条数
    long totalHits = searchHits.getTotalHits();
    // 所有结果中文档得分的最高分
    float maxScore = searchHits.getMaxScore();

    System.out.println("took:" + took);
    System.out.println("_shards:");
    System.out.println("        total:" + total);
    System.out.println("        success:" + success);
    System.out.println("        skipped:" + skipped);
    System.out.println("        failed:" + failed);
    System.out.println("hits:");
    System.out.println("        total:" + totalHits);
    System.out.println("        max_score:" + maxScore);
    System.out.println("        hits:");
    // 搜索结果的文档对象数组,每个元素是一条搜索到的文档信息
    SearchHit[] hits = searchHits.getHits();
    for (SearchHit hit : hits) {
        // 索引库
        String index = hit.getIndex();
        // 文档类型
        String type = hit.getType();
        // 文档id
        String id = hit.getId();
        // 文档得分
        float score = hit.getScore();
        // 文档的源数据
        String source = hit.getSourceAsString();
        System.out.println("            _index:" + index);
        System.out.println("            _type:" + type);
        System.out.println("            _id:" + id);
        System.out.println("            _score:" + score);
        System.out.println("            _source:" + source);
    }
    restHighLevelClient.close();
}
 
Example 5
Source File: EsHighLevelRestSearchTest.java    From java-study with Apache License 2.0 4 votes vote down vote up
/**
     * @return void
     * @Author pancm
     * @Description 普通查询
     * @Date 2019/9/12
     * @Param []
     **/
    private static void genSearch() throws IOException {
        String type = "_doc";
        String index = "test1";
        // 查询指定的索引库
        SearchRequest searchRequest = new SearchRequest(index);
        searchRequest.types(type);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 设置查询条件
        sourceBuilder.query(QueryBuilders.termQuery("uid", "1234"));
        // 设置起止和结束
        sourceBuilder.from(0);
        sourceBuilder.size(5);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        // 设置路由
//		searchRequest.routing("routing");
        // 设置索引库表达式
        searchRequest.indicesOptions(IndicesOptions.lenientExpandOpen());
        // 查询选择本地分片,默认是集群分片
        searchRequest.preference("_local");

        // 排序
        // 根据默认值进行降序排序
//		sourceBuilder.sort(new ScoreSortBuilder().order(SortOrder.DESC));
        // 根据字段进行升序排序
//		sourceBuilder.sort(new FieldSortBuilder("id").order(SortOrder.ASC));

        // 关闭suorce查询
//		sourceBuilder.fetchSource(false);

        String[] includeFields = new String[]{"title", "user", "innerObject.*"};
        String[] excludeFields = new String[]{"_type"};
        // 包含或排除字段
//		sourceBuilder.fetchSource(includeFields, excludeFields);

        searchRequest.source(sourceBuilder);
        System.out.println("普通查询的DSL语句:"+sourceBuilder.toString());
        // 同步查询
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        // HTTP状态代码、执行时间或请求是否提前终止或超时
        RestStatus status = searchResponse.status();
        TimeValue took = searchResponse.getTook();
        Boolean terminatedEarly = searchResponse.isTerminatedEarly();
        boolean timedOut = searchResponse.isTimedOut();

        // 供关于受搜索影响的切分总数的统计信息,以及成功和失败的切分
        int totalShards = searchResponse.getTotalShards();
        int successfulShards = searchResponse.getSuccessfulShards();
        int failedShards = searchResponse.getFailedShards();
        // 失败的原因
        for (ShardSearchFailure failure : searchResponse.getShardFailures()) {
            // failures should be handled here
        }
        // 结果
        searchResponse.getHits().forEach(hit -> {
            Map<String, Object> map = hit.getSourceAsMap();
            System.out.println("普通查询的结果:" + map);
        });
        System.out.println("\n=================\n");
    }
 
Example 6
Source File: CountResponse.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public CountResponse(SearchResponse searchResponse) {
    super(searchResponse.getTotalShards(), searchResponse.getSuccessfulShards(), searchResponse.getFailedShards(), Arrays.asList(searchResponse.getShardFailures()));
    this.count = searchResponse.getHits().totalHits();
    this.terminatedEarly = searchResponse.isTerminatedEarly() != null && searchResponse.isTerminatedEarly();
}
 
Example 7
Source File: Search.java    From elasticsearch-rest-command with The Unlicense 4 votes vote down vote up
public void executeQuery(final ActionListener<QueryResponse> listener,
		int from, final int size, String[] sortFields) {

	// jobHandler,执行期才知道要排序
	for (String field : sortFields) {
		if(field != null)	addSortToQuery(field);
	}

	querySearch.setSearchType(SearchType.QUERY_THEN_FETCH).setFrom(from)
			.setSize(size);
	dumpSearchScript(querySearch, logger);

	SearchResponse response = querySearch.execute().actionGet();
	logger.info(String.format("query took %d", response.getTookInMillis()));
	long milli = System.currentTimeMillis();

	final QueryResponse queryResponse = new QueryResponse(size);

	queryResponse.totalHits = response.getHits().getTotalHits();
	queryResponse.failedShards = response.getFailedShards();
	queryResponse.successfulShards = response.getSuccessfulShards();
	queryResponse.totalShards = response.getTotalShards();
	Iterator<SearchHit> iterator = response.getHits().iterator();

	while (iterator.hasNext()) {
		SearchHit _hit = iterator.next();
		Map<String, Object> hit = _hit.sourceAsMap();
		hit.put("_id", _hit.id());
		hit.put("_index", _hit.index());
		hit.put("_type", _hit.type());

		queryResponse.searchHits.add(hit);
	}

	for (Join join : joinSearchs) {
		try {
			JoinQuery.executeJoin(join, size, queryResponse.searchHits,
					client, logger);
		} catch (CommandException e) {
			logger.error("executeJoin", e);
			listener.onFailure(e);
			return;
		}
	}

	queryResponse.took = response.getTookInMillis()
			+ (System.currentTimeMillis() - milli);
	listener.onResponse(queryResponse);
}