Java Code Examples for org.elasticsearch.action.search.SearchRequest#types()

The following examples show how to use org.elasticsearch.action.search.SearchRequest#types() . 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: MultiMatchQueryApidMain.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{
        QueryBuilder matchQueryBuilder = QueryBuilders.multiMatchQuery("token","retdesc", "reqpkg");//查询有问题??

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

        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 2
Source File: CountRequest.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
public SearchRequest toSearchRequest() {
    SearchRequest searchRequest = new SearchRequest(indices());
    searchRequest.indicesOptions(indicesOptions());
    searchRequest.types(types());
    searchRequest.routing(routing());
    searchRequest.preference(preference());
    searchRequest.source(source());
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    searchSourceBuilder.size(0);
    if (minScore() != DEFAULT_MIN_SCORE) {
        searchSourceBuilder.minScore(minScore());
    }
    if (terminateAfter() != DEFAULT_TERMINATE_AFTER) {
        searchSourceBuilder.terminateAfter(terminateAfter());
    }
    searchRequest.extraSource(searchSourceBuilder);
    return searchRequest;
}
 
Example 3
Source File: SearchableImpl.java    From spring-content with Apache License 2.0 6 votes vote down vote up
@Override
public Iterable<Serializable> search(String queryStr) {
	SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
	searchRequest.types(domainClass.getName());

	SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
	sourceBuilder.query(QueryBuilders.simpleQueryStringQuery(queryStr));
	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'", queryStr), ioe);
	}

	return getIDs(res.getHits());
}
 
Example 4
Source File: PrefixApiMain.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{
        PrefixQueryBuilder matchQueryBuilder = QueryBuilders.prefixQuery("cmd","get_fee");//查询某个字段存在的记录

        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 5
Source File: ElasticsearchHighRestFactory.java    From database-transform-tool with Apache License 2.0 6 votes vote down vote up
public String selectAll(String indexs,String types,String condition){
	try {
		if(StringUtil.isEmpty(indexs))indexs="_all";
		if(xclient==null){
			init();
		}
		SearchSourceBuilder search = new SearchSourceBuilder();
		search.query(QueryBuilders.queryStringQuery(condition)); 
		search.explain(false);
		SearchRequest request = new SearchRequest();
		request.searchType(SearchType.DFS_QUERY_THEN_FETCH);
		request.source(search);
		request.indices(indexs.split(","));
		request.types(types.split(","));
		SearchResponse response = xclient.search(request);
		return response.toString();
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return null;
}
 
Example 6
Source File: TransportAddFeatureToSetAction.java    From elasticsearch-learning-to-rank with Apache License 2.0 6 votes vote down vote up
private void fetchFeaturesFromStore() {
    SearchRequest srequest = new SearchRequest(store);
    srequest.setParentTask(clusterService.localNode().getId(), task.getId());
    QueryBuilder nameQuery;

    if (featureNamesQuery.endsWith("*")) {
        String parsed = featureNamesQuery.replaceAll("[*]+$", "");
        if (parsed.isEmpty()) {
            nameQuery = QueryBuilders.matchAllQuery();
        } else {
            nameQuery = QueryBuilders.matchQuery("name.prefix", parsed);
        }
    } else {
        nameQuery = QueryBuilders.matchQuery("name", featureNamesQuery);
    }
    BoolQueryBuilder bq = QueryBuilders.boolQuery();
    bq.must(nameQuery);
    bq.must(QueryBuilders.matchQuery("type", StoredFeature.TYPE));
    srequest.types(IndexFeatureStore.ES_TYPE);
    srequest.source().query(bq);
    srequest.source().fetchSource(true);
    srequest.source().size(StoredFeatureSet.MAX_FEATURES);
    searchAction.execute(srequest, wrap(this::onSearchResponse, this::onSearchFailure));
}
 
Example 7
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 8
Source File: ExistApiMain.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{
        ExistsQueryBuilder matchQueryBuilder = QueryBuilders.existsQuery("retcode");//查询某个字段存在的记录

        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 9
Source File: MatchParseApiMain.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{
        QueryBuilder matchQueryBuilder = QueryBuilders.matchPhraseQuery("content","校车");

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

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

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


    }finally{
        HighLevelClient.close();
    }
}
 
Example 10
Source File: PercentilesAggregationMain.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{
            QueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("cmd", "weather_hourforcast");
            PercentilesAggregationBuilder aggregationBuilder = AggregationBuilders.percentiles("utm").field("utm").keyed(false);
//            PercentilesAggregationBuilder aggregationBuilder = AggregationBuilders.percentiles("utm").field("utm").percentiles(95,99,99.9).keyed(false);//自定义百分区间

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

            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(matchQueryBuilder);
            searchSourceBuilder.aggregation(aggregationBuilder);
            searchSourceBuilder.size(0);
            searchRequest.source(searchSourceBuilder);

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

        }finally{
            HighLevelClient.close();
        }
    }
 
Example 11
Source File: ElasticSearchRestDAOV5.java    From conductor with Apache License 2.0 5 votes vote down vote up
@Override
public List<EventExecution> getEventExecutions(String event) {
    try {
        Expression expression = Expression.fromString("event='" + event + "'");
        QueryBuilder queryBuilder = expression.getFilterBuilder();

        BoolQueryBuilder filterQuery = QueryBuilders.boolQuery().must(queryBuilder);
        QueryStringQueryBuilder stringQuery = QueryBuilders.queryStringQuery("*");
        BoolQueryBuilder query = QueryBuilders.boolQuery().must(stringQuery).must(filterQuery);

        // Create the searchObjectIdsViaExpression source
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(query);
        searchSourceBuilder.sort(new FieldSortBuilder("created").order(SortOrder.ASC));

        // Generate the actual request to send to ES.
        SearchRequest searchRequest = new SearchRequest(logIndexPrefix + "*");
        searchRequest.types(EVENT_DOC_TYPE);
        searchRequest.source(searchSourceBuilder);

        SearchResponse response = elasticSearchClient.search(searchRequest);

        return mapEventExecutionsResponse(response);
    } catch (Exception e) {
        logger.error("Failed to get executions for event: {}", event, e);
        throw new ApplicationException(ApplicationException.Code.BACKEND_ERROR, e.getMessage(), e);
    }
}
 
Example 12
Source File: ElasticEventsController.java    From logsniffer with GNU Lesser General Public License v3.0 5 votes vote down vote up
@RequestMapping(value = "/reports/eventSearch", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public void eventSearch(final HttpEntity<String> httpEntity,
		final HttpServletResponse response) throws IOException {
	long start = System.currentTimeMillis();
	String jsonRequest = httpEntity.getBody();
	final SearchRequest searchRequest = new SearchRequest(indexName);
	try {
		searchRequest.source(jsonRequest);
		searchRequest.types("event");
		SearchResponse r = clientTpl
				.executeWithClient(new ClientCallback<SearchResponse>() {
					@Override
					public SearchResponse execute(final Client client) {
						return client.search(searchRequest).actionGet();
					}
				});
		response.setContentType(MediaType.APPLICATION_JSON_VALUE);
		OutputStream responseStream = response.getOutputStream();
		XContentBuilder builder = XContentFactory
				.jsonBuilder(responseStream);
		builder.startObject();
		r.toXContent(builder, ToXContent.EMPTY_PARAMS);
		builder.endObject();
		builder.close();
		responseStream.close();
	} finally {
		logger.debug("Executed search in {}ms: {}",
				System.currentTimeMillis() - start, jsonRequest);
	}
}
 
Example 13
Source File: InternalEsClient.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * 非同期でドキュメントをマルチ検索.
 * 存在しないインデックスに対して本メソッドを使用すると、TransportSerializationExceptionがスローされるので注意すること
 * @param index インデックス名
 * @param type タイプ名
 * @param routingId routingId
 * @param queryList マルチ検索用のクエリ情報リスト
 * @return 非同期応答
 */
public ActionFuture<MultiSearchResponse> asyncMultiSearch(
        String index,
        String type,
        String routingId,
        List<Map<String, Object>> queryList) {
    MultiSearchRequest mrequest = new MultiSearchRequest();
    if (queryList == null || queryList.size() == 0) {
        throw new EsMultiSearchQueryParseException();
    }
    for (Map<String, Object> query : queryList) {
        SearchRequest req = new SearchRequest(index).searchType(SearchType.DEFAULT);
        if (type != null) {
            req.types(type);
        }
        // クエリ指定なしの場合はタイプに対する全件検索を行う
        if (query != null) {
            req.source(query);
        }
        if (routingFlag) {
            req = req.routing(routingId);
        }
        mrequest.add(req);
    }

    ActionFuture<MultiSearchResponse> ret = esTransportClient.multiSearch(mrequest);
    this.fireEvent(Event.afterRequest, index, type, null, JSONArray.toJSONString(queryList), "MultiSearch");
    return ret;
}
 
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: SumAggregationMain.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{
//            QueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("cmd", "weather_hourforcast");
            SumAggregationBuilder aggregationBuilder = AggregationBuilders.sum("utm").field("utm");

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

            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//            searchSourceBuilder.query(matchQueryBuilder);
            searchSourceBuilder.aggregation(aggregationBuilder);
            searchSourceBuilder.size(0);
            searchRequest.source(searchSourceBuilder);

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

            //统计结果
            Aggregations aggregations = searchResponse.getAggregations();
            Map<String, Aggregation> aggregationMap = aggregations.asMap();
            for(Map.Entry<String,Aggregation> each: aggregationMap.entrySet()){
                System.out.println(((ParsedSum)(each.getValue())).getValue());
            }

        }finally{
            HighLevelClient.close();
        }
    }
 
Example 16
Source File: ElasticSearcher.java    From jpress with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Page<Product> search(String keyword, int pageNum, int pageSize) {

    BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
    boolQueryBuilder.should(new MatchQueryBuilder("title", keyword));
    boolQueryBuilder.should(new MatchQueryBuilder("content", keyword));


    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
    sourceBuilder.from(pageNum * pageSize - pageSize);
    sourceBuilder.size(pageSize);
    sourceBuilder.query(boolQueryBuilder);

    SearchRequest searchRequest = new SearchRequest();
    searchRequest.source(sourceBuilder);
    searchRequest.indices(index);
    searchRequest.types(type);

    try {
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        if (response == null || response.getHits() == null || response.getHits().getTotalHits().value <= 0) {
            return null;
        }

        int total = (int) response.getHits().getTotalHits().value;

        List<Product> products = new ArrayList<>();
        response.getHits().forEach(hit -> {
            Product product = new Product();
            product.put(hit.getSourceAsMap());
            products.add(product);
        });

        return new Page<>(products, pageNum, pageSize, total / pageSize, total);

    } catch (Exception e) {
        LOG.error(e.toString(), e);
    }
    return null;
}
 
Example 17
Source File: ElasticSearchClient.java    From skywalking with Apache License 2.0 5 votes vote down vote up
public SearchResponse search(String indexName, SearchSourceBuilder searchSourceBuilder) throws IOException {
    indexName = formatIndexName(indexName);
    SearchRequest searchRequest = new SearchRequest(indexName);
    searchRequest.types(TYPE);
    searchRequest.source(searchSourceBuilder);
    return client.search(searchRequest);
}
 
Example 18
Source File: Select.java    From code with Apache License 2.0 5 votes vote down vote up
@Before
public void init() {
    //1.连接rest接口
    HttpHost http = new HttpHost("127.0.0.1", 9200, "http");
    RestClientBuilder builder = RestClient.builder(http);//rest构建器
    restHighLevelClient = new
            RestHighLevelClient(builder);//高级客户端对象
    //2.封装查询请求
    searchRequest = new SearchRequest("sku");
    searchRequest.types("doc"); //设置查询的类型
}
 
Example 19
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 20
Source File: IgnoreAuditUsersTest.java    From deprecated-security-advanced-modules with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void initSearchRequest() {
    sr = new SearchRequest();
    sr.indices("index1", "logstash*");
    sr.types("mytype", "logs");
}