Java Code Examples for org.elasticsearch.search.builder.SearchSourceBuilder#query()

The following examples show how to use org.elasticsearch.search.builder.SearchSourceBuilder#query() . 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: TestSchema.java    From kafka-connect-elasticsearch-source with Apache License 2.0 6 votes vote down vote up
public void testSearch() throws Exception {
    SearchRequest searchRequest = new SearchRequest();
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    searchSourceBuilder.query(QueryBuilders.matchAllQuery());
    searchRequest.source(searchSourceBuilder);
    searchRequest.indices("metricbeat-6.2.4-2018.05.20");
    SearchResponse searchResponse = es.getClient().search(searchRequest);
    SearchHits hits = searchResponse.getHits();
    SearchHit[] searchHits = hits.getHits();
    for (SearchHit hit : searchHits) {
        // do something with the SearchHit
        Map<String, Object> sourceAsMap = hit.getSourceAsMap();
        System.out.println(sourceAsMap);
        Schema schema = SchemaConverter.convertElasticMapping2AvroSchema(sourceAsMap, "test");
        schema.toString();
        Struct struct = StructConverter.convertElasticDocument2AvroStruct(sourceAsMap,schema);
        struct.toString();
    }

}
 
Example 2
Source File: WildcardApiMain.java    From elasticsearch-pool with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {

        RestHighLevelClient client = HighLevelClient.getInstance();
        try{
            WildcardQueryBuilder matchQueryBuilder = QueryBuilders.wildcardQuery("cmd","get_fee*");//cmd必须匹配指定的正则表达式,不能是包含关系

            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(matchQueryBuilder);
            searchSourceBuilder.from(0);
            searchSourceBuilder.size(1);

            SearchRequest searchRequest = new SearchRequest("serverlog_20180701");//限定index
            searchRequest.types("log");//限定type
            searchRequest.source(searchSourceBuilder);

            SearchResponse searchResponse = client.search(searchRequest);
            System.out.println(searchResponse);


        }finally{
            HighLevelClient.close();
        }
    }
 
Example 3
Source File: LocationRepositoryImpl.java    From bearchoke with Apache License 2.0 6 votes vote down vote up
/**
 * What we want this complex elasticsearch query to do is:
 * 1. Match user search input to the fields code, name and description
 * 2. If any of the documents are of type REGION --> boost document 4
 * 2. If any of the documents are of type CITY --> boost document 3
 * 3. If any of the documents are of type AIRPORT --> boost document 2
 * 4. If any of the documents are of type COUNTRY --> boost document 1
 * 4. If any of the documents are of type HOTEL --> no boost necessary
 *
 * @param userInput user input from search
 * @return
 */
public List<Location> locationSearch(String userInput) {
    List<Location> locations = null;

    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    searchSourceBuilder.query(QueryBuilders.queryStringQuery(userInput));

    Search search = new Search.Builder(searchSourceBuilder.toString())
            .addIndex(LOCATION_INDEX_NAME)
            .addType(LOCATION_INDEX_TYPE).build();

    try {
        JestResult result = jestClient.execute(search);

        locations = result.getSourceAsObjectList(Location.class);

    } catch (Exception e) {
        log.error(e.getMessage());
    }

    return locations;
}
 
Example 4
Source File: DownloadMaster.java    From occurrence with Apache License 2.0 6 votes vote down vote up
/**
 * Executes a search and get number of records.
 */
private Long getSearchCount(String query) {
  try {
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().size(0);
    if (!Strings.isNullOrEmpty(query)) {
      searchSourceBuilder.query(QueryBuilders.wrapperQuery(query));
    } else {
      searchSourceBuilder.query(QueryBuilders.matchAllQuery());
    }
    SearchResponse searchResponse = esClient.search(new SearchRequest().indices(esIndex).source(searchSourceBuilder), RequestOptions.DEFAULT);
    return searchResponse.getHits().getTotalHits();
  } catch (Exception e) {
    LOG.error("Error executing query", e);
    return 0L;
  }
}
 
Example 5
Source File: SearchableImpl.java    From spring-content with Apache License 2.0 6 votes vote down vote up
@Override
public Iterable<Serializable> findKeyword(String query) {
	SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
	searchRequest.types(domainClass.getName());

	SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
	sourceBuilder.query(QueryBuilders.queryStringQuery(query));
	searchRequest.source(sourceBuilder);

	SearchResponse res = null;
	try {
		res = client.search(searchRequest, RequestOptions.DEFAULT);
	}
	catch (IOException ioe) {
		throw new StoreAccessException(format("Error searching indexed content for '%s'", query), ioe);
	}

	return getIDs(res.getHits());
}
 
Example 6
Source File: EsHighLevelRestSearchTest.java    From java-study with Apache License 2.0 6 votes vote down vote up
/**
 * @Author pancm
 * @Description  正则查询
 * @Date  2019/9/30
 * @Param []
 * @return void
 **/
private static void regexpSearch() throws IOException{
    String type = "_doc";
    String index = "test1";
    // 查询指定的索引库
    SearchRequest searchRequest = new SearchRequest(index);
    searchRequest.types(type);
    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
    // 设置查询条件
    sourceBuilder.query(QueryBuilders.regexpQuery("message","xu[0-9]"));
    searchRequest.source(sourceBuilder);
    System.out.println("正则查询的DSL语句:"+sourceBuilder.toString());
    // 同步查询
    SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
    // 结果
    searchResponse.getHits().forEach(hit -> {
        Map<String, Object> map = hit.getSourceAsMap();
        String string = hit.getSourceAsString();
        System.out.println("正则查询的Map结果:" + map);
        System.out.println("正则查询的String结果:" + string);
    });

    System.out.println("\n=================\n");
}
 
Example 7
Source File: QueryHelper.java    From fast-elasticsearch-query-builder with Apache License 2.0 6 votes vote down vote up
public void set(SearchSourceBuilder searchSource) {
    BoolQueryBuilder boolQuery = boolQuery();

    if (orQueries().size() > 0 || orNotQueries().size() > 0) {
        BoolQueryBuilder orQuery = boolQuery();
        orQueries().forEach(orQuery::should);
        orNotQueries().forEach(t -> orQuery.should(boolQuery().mustNot(t)));
        filterQueries().add(orQuery);
    }

    mustQueries().forEach(boolQuery::must);
    mustNotQueries().forEach(boolQuery::mustNot);
    shouldQueries().forEach(boolQuery::should);
    filterQueries().forEach(boolQuery::filter);

    searchSource.query(boolQuery);
}
 
Example 8
Source File: TopologyQueryEsDAO.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public List<Call.CallDetail> loadServiceRelationDetectedAtClientSide(long startTB,
                                                                     long endTB) throws IOException {
    SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource();
    sourceBuilder.query(QueryBuilders.rangeQuery(ServiceRelationServerSideMetrics.TIME_BUCKET)
                                     .gte(startTB)
                                     .lte(endTB));
    sourceBuilder.size(0);

    return buildServiceRelation(sourceBuilder, ServiceRelationClientSideMetrics.INDEX_NAME, DetectPoint.CLIENT);
}
 
Example 9
Source File: ElasticsearchHelperService.java    From xmfcn-spring-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 按天Level统计  各个日志级别的数量 查询条件
 *
 * @param EsModel es
 *                keywords
 *                highlights
 * @return
 */
public Search statisticsLevelCondition(EsModel es) {
    Search search = null;
    if (es == null) {
        return search;
    }
    String indexName = es.getIndex();
    String type = es.getType();
    String startTime = es.getStartTime();
    String endTime = es.getEndTime();
    JSONObject keywords = es.getKeyWord();
    if (StringUtil.isBlank(indexName)) {
        return search;
    }
    if (StringUtil.isBlank(type)) {
        return search;
    }
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    if (StringUtil.isNotBlank(startTime) && StringUtil.isNotBlank(endTime)) {
        RangeQueryBuilder rangequerybuilder = QueryBuilders
                .rangeQuery("createTime")
                .from(startTime).to(endTime);
        searchSourceBuilder.query(rangequerybuilder);
    }
    AddKeyWords(keywords, searchSourceBuilder);
    ExtendedBounds extendedBounds = new ExtendedBounds(startTime, endTime);
    AggregationBuilder levelAgg = AggregationBuilders.terms("level_count").field("level").minDocCount(0);
    searchSourceBuilder.aggregation(levelAgg).size(0);
    search = new Search.Builder(searchSourceBuilder.toString())
            .addIndex(indexName).addType(type).build();
    return search;
}
 
Example 10
Source File: BoolApiMain.java    From elasticsearch-pool with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
        RestHighLevelClient client = HighLevelClient.getInstance();
        try{
            BoolQueryBuilder matchQueryBuilder = QueryBuilders.boolQuery();
            matchQueryBuilder.must(QueryBuilders.termQuery("cpname","llbxinterface"));
            matchQueryBuilder.mustNot(QueryBuilders.termQuery("status","fail"));
            matchQueryBuilder.should(QueryBuilders.rangeQuery("utm").from(0,true).to(100,true));
            matchQueryBuilder.minimumShouldMatch(1);
//            matchQueryBuilder.filter();

            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(matchQueryBuilder);
            searchSourceBuilder.from(0);
            searchSourceBuilder.size(3);

            SearchRequest searchRequest = new SearchRequest("serverlog_20180701");//限定index
            searchRequest.types("log");//限定type
            searchRequest.source(searchSourceBuilder);

            SearchResponse searchResponse = client.search(searchRequest);
            System.out.println(searchResponse);


        }finally{
            HighLevelClient.close();
        }
    }
 
Example 11
Source File: TopologyQueryEsDAO.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public List<Call.CallDetail> loadServiceRelationsDetectedAtServerSide(long startTB,
                                                                      long endTB) throws IOException {
    SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource();
    sourceBuilder.query(QueryBuilders.rangeQuery(ServiceRelationServerSideMetrics.TIME_BUCKET)
                                     .gte(startTB)
                                     .lte(endTB));
    sourceBuilder.size(0);

    return buildServiceRelation(sourceBuilder, ServiceRelationServerSideMetrics.INDEX_NAME, DetectPoint.SERVER);
}
 
Example 12
Source File: ElasticSearchRestDAOV5.java    From conductor with Apache License 2.0 5 votes vote down vote up
/**
 * Tries to find object ids for a given query in an index.
 *
 * @param indexName The name of the index.
 * @param queryBuilder The query to use for searching.
 * @param start The start to use.
 * @param size The total return size.
 * @param sortOptions A list of string options to sort in the form VALUE:ORDER; where ORDER is optional and can be either ASC OR DESC.
 * @param docType The document type to searchObjectIdsViaExpression for.
 *
 * @return The SearchResults which includes the count and IDs that were found.
 * @throws IOException If we cannot communicate with ES.
 */
private SearchResult<String> searchObjectIds(String indexName, QueryBuilder queryBuilder, int start, int size, List<String> sortOptions, String docType) throws IOException {

    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    searchSourceBuilder.query(queryBuilder);
    searchSourceBuilder.from(start);
    searchSourceBuilder.size(size);

    if (sortOptions != null && !sortOptions.isEmpty()) {

        for (String sortOption : sortOptions) {
            SortOrder order = SortOrder.ASC;
            String field = sortOption;
            int index = sortOption.indexOf(":");
            if (index > 0) {
                field = sortOption.substring(0, index);
                order = SortOrder.valueOf(sortOption.substring(index + 1));
            }
            searchSourceBuilder.sort(new FieldSortBuilder(field).order(order));
        }
    }

    // Generate the actual request to send to ES.
    SearchRequest searchRequest = new SearchRequest(indexName);
    searchRequest.types(docType);
    searchRequest.source(searchSourceBuilder);

    SearchResponse response = elasticSearchClient.search(searchRequest);

    List<String> result = new LinkedList<>();
    response.getHits().forEach(hit -> result.add(hit.getId()));
    long count = response.getHits().getTotalHits();
    return new SearchResult<>(count, result);
}
 
Example 13
Source File: SearchQueryProcessor.java    From occurrence with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a search query that contains the query parameter as the filter query value.
 */
private static SearchSourceBuilder createSearchQuery(String query) {
  SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  if (!Strings.isNullOrEmpty(query)) {
    searchSourceBuilder.query(QueryBuilders.wrapperQuery(query));
  }
  //key is required since this runs in a distributed installations where the natural order can't be guaranteed
  searchSourceBuilder.sort(KEY_FIELD, SortOrder.DESC);
  return searchSourceBuilder;
}
 
Example 14
Source File: ElasticSearchRestDAOV6.java    From conductor with Apache License 2.0 5 votes vote down vote up
/**
 * Tries to find object ids for a given query in an index.
 *
 * @param indexName    The name of the index.
 * @param queryBuilder The query to use for searching.
 * @param start        The start to use.
 * @param size         The total return size.
 * @param sortOptions  A list of string options to sort in the form VALUE:ORDER; where ORDER is optional and can be
 *                     either ASC OR DESC.
 * @param docType      The document type to searchObjectIdsViaExpression for.
 * @return The SearchResults which includes the count and IDs that were found.
 * @throws IOException If we cannot communicate with ES.
 */
private SearchResult<String> searchObjectIds(String indexName, QueryBuilder queryBuilder, int start, int size,
    List<String> sortOptions, String docType) throws IOException {
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    searchSourceBuilder.query(queryBuilder);
    searchSourceBuilder.from(start);
    searchSourceBuilder.size(size);

    if (sortOptions != null && !sortOptions.isEmpty()) {

        for (String sortOption : sortOptions) {
            SortOrder order = SortOrder.ASC;
            String field = sortOption;
            int index = sortOption.indexOf(":");
            if (index > 0) {
                field = sortOption.substring(0, index);
                order = SortOrder.valueOf(sortOption.substring(index + 1));
            }
            searchSourceBuilder.sort(new FieldSortBuilder(field).order(order));
        }
    }

    // Generate the actual request to send to ES.
    docType = StringUtils.isBlank(docTypeOverride) ? docType : docTypeOverride;
    SearchRequest searchRequest = new SearchRequest(indexName);
    searchRequest.types(docType);
    searchRequest.source(searchSourceBuilder);

    SearchResponse response = elasticSearchClient.search(searchRequest);

    List<String> result = new LinkedList<>();
    response.getHits().forEach(hit -> result.add(hit.getId()));
    long count = response.getHits().getTotalHits();
    return new SearchResult<>(count, result);
}
 
Example 15
Source File: ElasticsearchHelperService.java    From xmfcn-spring-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 按天统计  各个日志级别的数量 查询条件
 *
 * @param EsModel es
 *                keywords
 *                highlights
 * @return
 */
public Search statisticsDayCondition(EsModel es) {
    Search search = null;
    if (es == null) {
        return search;
    }
    String indexName = es.getIndex();
    String type = es.getType();
    String startTime = es.getStartTime();
    String endTime = es.getEndTime();
    JSONObject keywords = es.getKeyWord();
    if (StringUtil.isBlank(indexName)) {
        return search;
    }
    if (StringUtil.isBlank(type)) {
        return search;
    }
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    if (StringUtil.isNotBlank(startTime) && StringUtil.isNotBlank(endTime)) {
        RangeQueryBuilder rangequerybuilder = QueryBuilders
                .rangeQuery("createTime")
                .from(startTime).to(endTime);
        searchSourceBuilder.query(rangequerybuilder);
    }
    AddKeyWords(keywords, searchSourceBuilder);
    ExtendedBounds extendedBounds = new ExtendedBounds(startTime, endTime);
    AggregationBuilder levelAgg = AggregationBuilders.terms("level_count").field("level").minDocCount(0);
    AggregationBuilder dateAgg = AggregationBuilders.dateHistogram("day_count")
            .field("createTime")
            .dateHistogramInterval(DateHistogramInterval.DAY)
            .format("yyyy-MM-dd")
            .extendedBounds(extendedBounds)
            .minDocCount(0L)//为空0补充
            .timeZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("GMT+8")));
    AggregationBuilder builder = dateAgg.subAggregation(levelAgg);
    searchSourceBuilder.aggregation(builder).size(0);
    search = new Search.Builder(searchSourceBuilder.toString())
            .addIndex(indexName).addType(type).build();
    return search;
}
 
Example 16
Source File: ScrollSpout.java    From storm-crawler with Apache License 2.0 5 votes vote down vote up
@Override
protected void populateBuffer() {
    if (hasFinished) {
        Utils.sleep(10);
        return;
    }

    // initial request
    if (scrollId == null) {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        searchSourceBuilder.size(maxURLsPerBucket * maxBucketNum);
        SearchRequest searchRequest = new SearchRequest(indexName);
        searchRequest.source(searchSourceBuilder);
        searchRequest.scroll(TimeValue.timeValueMinutes(5L));

        if (shardID != -1) {
            searchRequest.preference("_shards:" + shardID);
        }

        isInQuery.set(true);
        client.searchAsync(searchRequest, RequestOptions.DEFAULT, this);

        // dump query to log
        LOG.debug("{} ES query {}", logIdprefix, searchRequest.toString());
        return;
    }

    SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId);
    scrollRequest.scroll(TimeValue.timeValueMinutes(5L));

    isInQuery.set(true);
    client.scrollAsync(scrollRequest, RequestOptions.DEFAULT, this);
    // dump query to log
    LOG.debug("{} ES query {}", logIdprefix, scrollRequest.toString());
}
 
Example 17
Source File: HighLevelRestController.java    From ProjectStudy with MIT License 5 votes vote down vote up
/**
   * 列表查询
   *
   * @param page
* @param rows
* @param keyword
   * @return com.example.common.ResponseBean
   * @throws
   * @author wliduo[[email protected]]
   * @date 2019/8/15 16:01
   */
  @GetMapping("/book")
  public ResponseBean list(@RequestParam(defaultValue = "1") Integer page,
                           @RequestParam(defaultValue = "10") Integer rows,
                           String keyword) throws IOException {
      SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
      // 分页采用简单的from + size分页,适用数据量小的,了解更多分页方式可自行查阅资料
      searchSourceBuilder.from((page - 1) * rows);
      searchSourceBuilder.size(rows);
      // 查询条件,只有查询关键字不为空才带查询条件
      if (StringUtils.isNoneBlank(keyword)) {
          QueryBuilder queryBuilder = QueryBuilders.multiMatchQuery(keyword, "name", "desc");
          searchSourceBuilder.query(queryBuilder);
      }
      // 排序,根据ID倒叙
      searchSourceBuilder.sort("id", SortOrder.DESC);
      // SearchRequest
      SearchRequest searchRequest = new SearchRequest();
      searchRequest.source(searchSourceBuilder);
      // 查询ES
      SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
      SearchHits hits = searchResponse.getHits();
      // 获取总数
      Long total = hits.getTotalHits().value;
      // 遍历封装列表对象
      List<BookDto> bookDtoList = new ArrayList<>();
      SearchHit[] searchHits = hits.getHits();
      for (SearchHit searchHit : searchHits) {
          bookDtoList.add(JSON.parseObject(searchHit.getSourceAsString(), BookDto.class));
      }
      // 封装Map参数返回
      Map<String, Object> result = new HashMap<String, Object>(16);
      result.put("count", total);
      result.put("data", bookDtoList);
      return new ResponseBean(HttpStatus.OK.value(), "查询成功", result);
  }
 
Example 18
Source File: Test.java    From dht-spider with MIT License 5 votes vote down vote up
public static void search(Map<String, Object> m) throws Exception{

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(5);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        searchSourceBuilder.query(QueryBuilders.termQuery("message", "视频"));

        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("torrent");
        searchRequest.source(searchSourceBuilder);


        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        RestStatus status = searchResponse.status();
        TimeValue took = searchResponse.getTook();
        Boolean terminatedEarly = searchResponse.isTerminatedEarly();
        boolean timedOut = searchResponse.isTimedOut();
        SearchHits hits = searchResponse.getHits();
        SearchHit[] searchHits = hits.getHits();
        for (SearchHit hit : searchHits) {
            // do something with the SearchHit
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            System.out.print(sourceAsMap+"===");
        }


    }
 
Example 19
Source File: ElasticsearchRestClientInstrumentationIT.java    From apm-agent-java with Apache License 2.0 4 votes vote down vote up
@Test
public void testDocumentScenario() throws IOException, ExecutionException, InterruptedException {
    // Index a document
    IndexResponse ir = doIndex(new IndexRequest(INDEX, DOC_TYPE, DOC_ID).source(
        jsonBuilder()
            .startObject()
            .field(FOO, BAR)
            .endObject()
    ).setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE));
    assertThat(ir.status().getStatus()).isEqualTo(201);


    List<Span> spans = reporter.getSpans();
    assertThat(spans).hasSize(1);
    validateSpanContent(spans.get(0), String.format("Elasticsearch: PUT /%s/%s/%s", INDEX, DOC_TYPE, DOC_ID), 201, "PUT");

    // Search the index
    reporter.reset();

    SearchRequest searchRequest = new SearchRequest(INDEX);
    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
    sourceBuilder.query(QueryBuilders.termQuery(FOO, BAR));
    sourceBuilder.from(0);
    sourceBuilder.size(5);
    searchRequest.source(sourceBuilder);
    SearchResponse sr = doSearch(searchRequest);
    assertThat(sr.getHits().totalHits).isEqualTo(1L);
    assertThat(sr.getHits().getAt(0).getSourceAsMap().get(FOO)).isEqualTo(BAR);


    spans = reporter.getSpans();
    assertThat(spans).hasSize(1);
    Span searchSpan = spans.get(0);
    validateSpanContent(searchSpan, String.format("Elasticsearch: GET /%s/_search", INDEX), 200, "GET");
    validateDbContextContent(searchSpan, "{\"from\":0,\"size\":5,\"query\":{\"term\":{\"foo\":{\"value\":\"bar\",\"boost\":1.0}}}}");

    // Now update and re-search
    reporter.reset();

    Map<String, Object> jsonMap = new HashMap<>();
    jsonMap.put(FOO, BAZ);
    UpdateResponse ur = doUpdate(new UpdateRequest(INDEX, DOC_TYPE, DOC_ID).doc(jsonMap)
        .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE));
    assertThat(ur.status().getStatus()).isEqualTo(200);
    sr = doSearch(new SearchRequest(INDEX));
    assertThat(sr.getHits().getAt(0).getSourceAsMap().get(FOO)).isEqualTo(BAZ);


    spans = reporter.getSpans();
    assertThat(spans).hasSize(2);
    boolean updateSpanFound = false;
    for(Span span: spans) {
        if(span.getNameAsString().contains("_update")) {
            updateSpanFound = true;
            break;
        }
    }
    assertThat(updateSpanFound).isTrue();

    // Finally - delete the document
    reporter.reset();
    DeleteResponse dr = doDelete(new DeleteRequest(INDEX, DOC_TYPE, DOC_ID));
    validateSpanContent(spans.get(0), String.format("Elasticsearch: DELETE /%s/%s/%s", INDEX, DOC_TYPE, DOC_ID), 200, "DELETE");
}
 
Example 20
Source File: EsUtil.java    From java-study with Apache License 2.0 4 votes vote down vote up
/**
 * @return boolean
 * @Author pancm
 * @Description 根据条件查询
 * @Date 2019/3/21
 * @Param []
 **/
public static List<Map<String, Object>> query(String index, String type, EsQueryCondition esQueryCondition, QueryBuilder... queryBuilders) throws IOException {
    if (index == null || type == null) {
        return null;
    }
    List<Map<String, Object>> list = new ArrayList<>();
    try {
        // 查询指定的索引库
        SearchRequest searchRequest = new SearchRequest(index);
        searchRequest.types(type);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        if (esQueryCondition != null) {
            Integer form = esQueryCondition.getIndex();
            Integer pagesize = esQueryCondition.getPagesize();
            if (form != null && form > 0 && pagesize != null && pagesize > 0) {
                form = (form - 1) * pagesize;
                pagesize = form + pagesize;
                // 设置起止和结束
                sourceBuilder.from(form);
                sourceBuilder.size(pagesize);
            }
            String routing = esQueryCondition.getRouting();
            if (routing != null && routing.length() > 0) {
                // 设置路由
                searchRequest.routing(routing);
            }

            // 设置索引库表达式
            searchRequest.indicesOptions(IndicesOptions.lenientExpandOpen());

            //设置排序
            String order = esQueryCondition.getOrder();
            if (order != null) {
                String[] orderField = esQueryCondition.getOrderField();
                SortOrder order2 = order.equals(SortOrder.DESC) ? SortOrder.DESC : SortOrder.ASC;
                //如果设置了排序字段则用排序的字段进行排序,否则就默认排序
                if (orderField != null) {
                    for (String field : orderField) {
                        sourceBuilder.sort(new FieldSortBuilder(field).order(order2));
                    }
                } else {
                    sourceBuilder.sort(new ScoreSortBuilder().order(order2));
                }
            }
            String[] includeFields = esQueryCondition.getIncludeFields();
            String[] excludeFields = esQueryCondition.getExcludeFields();
            if (includeFields != null && includeFields.length > 0 && excludeFields != null && excludeFields.length > 0) {
                sourceBuilder.fetchSource(includeFields, excludeFields);
            }
            sourceBuilder.fetchSource(esQueryCondition.isCloseSource());
        }
        //设置条件
        if (queryBuilders != null) {
            for (QueryBuilder queryBuilder : queryBuilders) {
                sourceBuilder.query(queryBuilder);
            }
        }

        searchRequest.source(sourceBuilder);
        // 同步查询
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        if(queryBuilders != null|| (esQueryCondition != null && esQueryCondition.isQueryData())){
            // 结果
            searchResponse.getHits().forEach(hit -> {
                Map<String, Object> map = hit.getSourceAsMap();
                list.add(map);
            });
        }

          if(esQueryCondition != null && esQueryCondition.isNeedTotal()){
              Map<String, Object> mapTotal = new HashMap<>();
              mapTotal.put("total", searchResponse.getHits().getTotalHits());
              list.add(mapTotal);
          }

    } finally {
        if (isAutoClose) {
            close();
        }
    }
    return list;
}