Search in sources :

Example 6 with SearchSourceBuilder

use of org.elasticsearch.search.builder.SearchSourceBuilder in project elasticsearch by elastic.

the class RestCountAction method prepareRequest.

@Override
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
    SearchRequest countRequest = new SearchRequest(Strings.splitStringByCommaToArray(request.param("index")));
    countRequest.indicesOptions(IndicesOptions.fromRequest(request, countRequest.indicesOptions()));
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().size(0);
    countRequest.source(searchSourceBuilder);
    request.withContentOrSourceParamParserOrNull(parser -> {
        if (parser == null) {
            QueryBuilder queryBuilder = RestActions.urlParamsToQueryBuilder(request);
            if (queryBuilder != null) {
                searchSourceBuilder.query(queryBuilder);
            }
        } else {
            searchSourceBuilder.query(RestActions.getQueryContent(parser));
        }
    });
    countRequest.routing(request.param("routing"));
    float minScore = request.paramAsFloat("min_score", -1f);
    if (minScore != -1f) {
        searchSourceBuilder.minScore(minScore);
    }
    countRequest.types(Strings.splitStringByCommaToArray(request.param("type")));
    countRequest.preference(request.param("preference"));
    final int terminateAfter = request.paramAsInt("terminate_after", DEFAULT_TERMINATE_AFTER);
    if (terminateAfter < 0) {
        throw new IllegalArgumentException("terminateAfter must be > 0");
    } else if (terminateAfter > 0) {
        searchSourceBuilder.terminateAfter(terminateAfter);
    }
    return channel -> client.search(countRequest, new RestBuilderListener<SearchResponse>(channel) {

        @Override
        public RestResponse buildResponse(SearchResponse response, XContentBuilder builder) throws Exception {
            builder.startObject();
            if (terminateAfter != DEFAULT_TERMINATE_AFTER) {
                builder.field("terminated_early", response.isTerminatedEarly());
            }
            builder.field("count", response.getHits().getTotalHits());
            buildBroadcastShardsHeader(builder, request, response.getTotalShards(), response.getSuccessfulShards(), response.getFailedShards(), response.getShardFailures());
            builder.endObject();
            return new BytesRestResponse(response.status(), builder);
        }
    });
}
Also used : BaseRestHandler(org.elasticsearch.rest.BaseRestHandler) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) GET(org.elasticsearch.rest.RestRequest.Method.GET) RestResponse(org.elasticsearch.rest.RestResponse) RestBuilderListener(org.elasticsearch.rest.action.RestBuilderListener) IOException(java.io.IOException) SearchRequest(org.elasticsearch.action.search.SearchRequest) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) RestController(org.elasticsearch.rest.RestController) Strings(org.elasticsearch.common.Strings) RestActions(org.elasticsearch.rest.action.RestActions) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) DEFAULT_TERMINATE_AFTER(org.elasticsearch.search.internal.SearchContext.DEFAULT_TERMINATE_AFTER) POST(org.elasticsearch.rest.RestRequest.Method.POST) Settings(org.elasticsearch.common.settings.Settings) RestActions.buildBroadcastShardsHeader(org.elasticsearch.rest.action.RestActions.buildBroadcastShardsHeader) SearchResponse(org.elasticsearch.action.search.SearchResponse) IndicesOptions(org.elasticsearch.action.support.IndicesOptions) RestRequest(org.elasticsearch.rest.RestRequest) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder) NodeClient(org.elasticsearch.client.node.NodeClient) SearchRequest(org.elasticsearch.action.search.SearchRequest) RestResponse(org.elasticsearch.rest.RestResponse) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) IOException(java.io.IOException) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder) SearchResponse(org.elasticsearch.action.search.SearchResponse) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder)

Example 7 with SearchSourceBuilder

use of org.elasticsearch.search.builder.SearchSourceBuilder in project elasticsearch by elastic.

the class SimpleQueryStringIT method testSimpleQueryStringFlags.

public void testSimpleQueryStringFlags() throws ExecutionException, InterruptedException {
    createIndex("test");
    indexRandom(true, client().prepareIndex("test", "type1", "1").setSource("body", "foo"), client().prepareIndex("test", "type1", "2").setSource("body", "bar"), client().prepareIndex("test", "type1", "3").setSource("body", "foo bar"), client().prepareIndex("test", "type1", "4").setSource("body", "quux baz eggplant"), client().prepareIndex("test", "type1", "5").setSource("body", "quux baz spaghetti"), client().prepareIndex("test", "type1", "6").setSource("otherbody", "spaghetti"));
    SearchResponse searchResponse = client().prepareSearch().setQuery(simpleQueryStringQuery("foo bar").flags(SimpleQueryStringFlag.ALL)).get();
    assertHitCount(searchResponse, 3L);
    assertSearchHits(searchResponse, "1", "2", "3");
    searchResponse = client().prepareSearch().setQuery(simpleQueryStringQuery("foo | bar").defaultOperator(Operator.AND).flags(SimpleQueryStringFlag.OR)).get();
    assertHitCount(searchResponse, 3L);
    assertSearchHits(searchResponse, "1", "2", "3");
    searchResponse = client().prepareSearch().setQuery(simpleQueryStringQuery("foo | bar").defaultOperator(Operator.AND).flags(SimpleQueryStringFlag.NONE)).get();
    assertHitCount(searchResponse, 1L);
    assertFirstHit(searchResponse, hasId("3"));
    searchResponse = client().prepareSearch().setQuery(simpleQueryStringQuery("baz | egg*").defaultOperator(Operator.AND).flags(SimpleQueryStringFlag.NONE)).get();
    assertHitCount(searchResponse, 0L);
    searchResponse = client().prepareSearch().setSource(new SearchSourceBuilder().query(QueryBuilders.simpleQueryStringQuery("foo|bar").defaultOperator(Operator.AND).flags(SimpleQueryStringFlag.NONE))).get();
    assertHitCount(searchResponse, 1L);
    searchResponse = client().prepareSearch().setQuery(simpleQueryStringQuery("quuz~1 + egg*").flags(SimpleQueryStringFlag.WHITESPACE, SimpleQueryStringFlag.AND, SimpleQueryStringFlag.FUZZY, SimpleQueryStringFlag.PREFIX)).get();
    assertHitCount(searchResponse, 1L);
    assertFirstHit(searchResponse, hasId("4"));
}
Also used : SearchResponse(org.elasticsearch.action.search.SearchResponse) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder)

Example 8 with SearchSourceBuilder

use of org.elasticsearch.search.builder.SearchSourceBuilder in project elasticsearch by elastic.

the class GeoDistanceSortBuilderIT method testSinglePointGeoDistanceSort.

public void testSinglePointGeoDistanceSort() throws ExecutionException, InterruptedException, IOException {
    assertAcked(prepareCreate("index").addMapping("type", LOCATION_FIELD, "type=geo_point"));
    indexRandom(true, client().prepareIndex("index", "type", "d1").setSource(jsonBuilder().startObject().startObject(LOCATION_FIELD).field("lat", 1).field("lon", 1).endObject().endObject()), client().prepareIndex("index", "type", "d2").setSource(jsonBuilder().startObject().startObject(LOCATION_FIELD).field("lat", 1).field("lon", 2).endObject().endObject()));
    String hashPoint = "s037ms06g7h0";
    GeoDistanceSortBuilder geoDistanceSortBuilder = new GeoDistanceSortBuilder(LOCATION_FIELD, hashPoint);
    SearchResponse searchResponse = client().prepareSearch().setQuery(matchAllQuery()).addSort(geoDistanceSortBuilder.sortMode(SortMode.MIN).order(SortOrder.ASC)).execute().actionGet();
    checkCorrectSortOrderForGeoSort(searchResponse);
    geoDistanceSortBuilder = new GeoDistanceSortBuilder(LOCATION_FIELD, new GeoPoint(2, 2));
    searchResponse = client().prepareSearch().setQuery(matchAllQuery()).addSort(geoDistanceSortBuilder.sortMode(SortMode.MIN).order(SortOrder.ASC)).execute().actionGet();
    checkCorrectSortOrderForGeoSort(searchResponse);
    geoDistanceSortBuilder = new GeoDistanceSortBuilder(LOCATION_FIELD, 2, 2);
    searchResponse = client().prepareSearch().setQuery(matchAllQuery()).addSort(geoDistanceSortBuilder.sortMode(SortMode.MIN).order(SortOrder.ASC)).execute().actionGet();
    checkCorrectSortOrderForGeoSort(searchResponse);
    searchResponse = client().prepareSearch().setSource(new SearchSourceBuilder().sort(SortBuilders.geoDistanceSort(LOCATION_FIELD, 2.0, 2.0))).execute().actionGet();
    checkCorrectSortOrderForGeoSort(searchResponse);
    searchResponse = client().prepareSearch().setSource(new SearchSourceBuilder().sort(SortBuilders.geoDistanceSort(LOCATION_FIELD, "s037ms06g7h0"))).execute().actionGet();
    checkCorrectSortOrderForGeoSort(searchResponse);
    searchResponse = client().prepareSearch().setSource(new SearchSourceBuilder().sort(SortBuilders.geoDistanceSort(LOCATION_FIELD, 2.0, 2.0))).execute().actionGet();
    checkCorrectSortOrderForGeoSort(searchResponse);
    searchResponse = client().prepareSearch().setSource(new SearchSourceBuilder().sort(SortBuilders.geoDistanceSort(LOCATION_FIELD, 2.0, 2.0).validation(GeoValidationMethod.COERCE))).execute().actionGet();
    checkCorrectSortOrderForGeoSort(searchResponse);
}
Also used : GeoPoint(org.elasticsearch.common.geo.GeoPoint) SearchResponse(org.elasticsearch.action.search.SearchResponse) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder)

Example 9 with SearchSourceBuilder

use of org.elasticsearch.search.builder.SearchSourceBuilder in project elasticsearch by elastic.

the class StoredExpressionTests method testAllOpsDisabledIndexedScripts.

public void testAllOpsDisabledIndexedScripts() throws IOException {
    client().admin().cluster().preparePutStoredScript().setLang(ExpressionScriptEngineService.NAME).setId("script1").setContent(new BytesArray("{\"script\":\"2\"}"), XContentType.JSON).get();
    client().prepareIndex("test", "scriptTest", "1").setSource("{\"theField\":\"foo\"}", XContentType.JSON).get();
    try {
        client().prepareUpdate("test", "scriptTest", "1").setScript(new Script(ScriptType.STORED, ExpressionScriptEngineService.NAME, "script1", Collections.emptyMap())).get();
        fail("update script should have been rejected");
    } catch (Exception e) {
        assertThat(e.getMessage(), containsString("failed to execute script"));
        assertThat(e.getCause().getMessage(), containsString("scripts of type [stored], operation [update] and lang [expression] are not supported"));
    }
    try {
        client().prepareSearch().setSource(new SearchSourceBuilder().scriptField("test1", new Script(ScriptType.STORED, "expression", "script1", Collections.emptyMap()))).setIndices("test").setTypes("scriptTest").get();
        fail("search script should have been rejected");
    } catch (Exception e) {
        assertThat(e.toString(), containsString("scripts of type [stored], operation [search] and lang [expression] are disabled"));
    }
    try {
        client().prepareSearch("test").setSource(new SearchSourceBuilder().aggregation(AggregationBuilders.terms("test").script(new Script(ScriptType.STORED, "expression", "script1", Collections.emptyMap())))).get();
    } catch (Exception e) {
        assertThat(e.toString(), containsString("scripts of type [stored], operation [aggs] and lang [expression] are disabled"));
    }
}
Also used : Script(org.elasticsearch.script.Script) BytesArray(org.elasticsearch.common.bytes.BytesArray) IOException(java.io.IOException) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder)

Example 10 with SearchSourceBuilder

use of org.elasticsearch.search.builder.SearchSourceBuilder in project elasticsearch by elastic.

the class RemoteRequestBuildersTests method testInitialSearchParamsSort.

public void testInitialSearchParamsSort() {
    SearchRequest searchRequest = new SearchRequest().source(new SearchSourceBuilder());
    // Test sort:_doc for versions that support it.
    Version remoteVersion = Version.fromId(between(Version.V_2_1_0_ID, Version.CURRENT.id));
    searchRequest.source().sort("_doc");
    assertThat(initialSearchParams(searchRequest, remoteVersion), hasEntry("sort", "_doc:asc"));
    // Test search_type scan for versions that don't support sort:_doc.
    remoteVersion = Version.fromId(between(0, Version.V_2_1_0_ID - 1));
    assertThat(initialSearchParams(searchRequest, remoteVersion), hasEntry("search_type", "scan"));
    // Test sorting by some field. Version doesn't matter.
    remoteVersion = Version.fromId(between(0, Version.CURRENT.id));
    searchRequest.source().sorts().clear();
    searchRequest.source().sort("foo");
    assertThat(initialSearchParams(searchRequest, remoteVersion), hasEntry("sort", "foo:asc"));
}
Also used : SearchRequest(org.elasticsearch.action.search.SearchRequest) Version(org.elasticsearch.Version) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder)

Aggregations

SearchSourceBuilder (org.elasticsearch.search.builder.SearchSourceBuilder)152 SearchResponse (org.elasticsearch.action.search.SearchResponse)77 SearchRequest (org.elasticsearch.action.search.SearchRequest)52 ElasticsearchAssertions.assertSearchResponse (org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse)37 Matchers.containsString (org.hamcrest.Matchers.containsString)32 IOException (java.io.IOException)31 QueryBuilder (org.elasticsearch.index.query.QueryBuilder)28 BoolQueryBuilder (org.elasticsearch.index.query.BoolQueryBuilder)26 List (java.util.List)25 SearchSourceBuilder (org.graylog.shaded.elasticsearch6.org.elasticsearch.search.builder.SearchSourceBuilder)24 SearchSourceBuilder (org.graylog.shaded.elasticsearch7.org.elasticsearch.search.builder.SearchSourceBuilder)24 Search (io.searchbox.core.Search)23 Map (java.util.Map)23 Set (java.util.Set)19 ArrayList (java.util.ArrayList)18 Collectors (java.util.stream.Collectors)18 Test (org.junit.Test)18 Collections (java.util.Collections)15 SearchHit (org.elasticsearch.search.SearchHit)15 TermsAggregationBuilder (org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder)15