Search in sources :

Example 76 with SearchHits

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.search.SearchHits in project elasticsearch by elastic.

the class TopHitsIT method testTopHitsInNestedSimple.

public void testTopHitsInNestedSimple() throws Exception {
    SearchResponse searchResponse = client().prepareSearch("articles").setQuery(matchQuery("title", "title")).addAggregation(nested("to-comments", "comments").subAggregation(terms("users").field("comments.user").subAggregation(topHits("top-comments").sort("comments.date", SortOrder.ASC)))).get();
    Nested nested = searchResponse.getAggregations().get("to-comments");
    assertThat(nested.getDocCount(), equalTo(4L));
    Terms terms = nested.getAggregations().get("users");
    Terms.Bucket bucket = terms.getBucketByKey("a");
    assertThat(bucket.getDocCount(), equalTo(1L));
    TopHits topHits = bucket.getAggregations().get("top-comments");
    SearchHits searchHits = topHits.getHits();
    assertThat(searchHits.getTotalHits(), equalTo(1L));
    assertThat(searchHits.getAt(0).getNestedIdentity().getField().string(), equalTo("comments"));
    assertThat(searchHits.getAt(0).getNestedIdentity().getOffset(), equalTo(0));
    assertThat((Integer) searchHits.getAt(0).getSourceAsMap().get("date"), equalTo(1));
    bucket = terms.getBucketByKey("b");
    assertThat(bucket.getDocCount(), equalTo(2L));
    topHits = bucket.getAggregations().get("top-comments");
    searchHits = topHits.getHits();
    assertThat(searchHits.getTotalHits(), equalTo(2L));
    assertThat(searchHits.getAt(0).getNestedIdentity().getField().string(), equalTo("comments"));
    assertThat(searchHits.getAt(0).getNestedIdentity().getOffset(), equalTo(1));
    assertThat((Integer) searchHits.getAt(0).getSourceAsMap().get("date"), equalTo(2));
    assertThat(searchHits.getAt(1).getNestedIdentity().getField().string(), equalTo("comments"));
    assertThat(searchHits.getAt(1).getNestedIdentity().getOffset(), equalTo(0));
    assertThat((Integer) searchHits.getAt(1).getSourceAsMap().get("date"), equalTo(3));
    bucket = terms.getBucketByKey("c");
    assertThat(bucket.getDocCount(), equalTo(1L));
    topHits = bucket.getAggregations().get("top-comments");
    searchHits = topHits.getHits();
    assertThat(searchHits.getTotalHits(), equalTo(1L));
    assertThat(searchHits.getAt(0).getNestedIdentity().getField().string(), equalTo("comments"));
    assertThat(searchHits.getAt(0).getNestedIdentity().getOffset(), equalTo(1));
    assertThat((Integer) searchHits.getAt(0).getSourceAsMap().get("date"), equalTo(4));
}
Also used : TopHits(org.elasticsearch.search.aggregations.metrics.tophits.TopHits) Nested(org.elasticsearch.search.aggregations.bucket.nested.Nested) Terms(org.elasticsearch.search.aggregations.bucket.terms.Terms) SearchHits(org.elasticsearch.search.SearchHits) SearchResponse(org.elasticsearch.action.search.SearchResponse) ElasticsearchAssertions.assertSearchResponse(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse)

Example 77 with SearchHits

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.search.SearchHits in project elasticsearch by elastic.

the class DuelScrollIT method testDuelQueryThenFetch.

public void testDuelQueryThenFetch() throws Exception {
    TestContext context = create(SearchType.DFS_QUERY_THEN_FETCH, SearchType.QUERY_THEN_FETCH);
    SearchResponse control = client().prepareSearch("index").setSearchType(context.searchType).addSort(context.sort).setSize(context.numDocs).get();
    assertNoFailures(control);
    SearchHits sh = control.getHits();
    assertThat(sh.getTotalHits(), equalTo((long) context.numDocs));
    assertThat(sh.getHits().length, equalTo(context.numDocs));
    SearchResponse searchScrollResponse = client().prepareSearch("index").setSearchType(context.searchType).addSort(context.sort).setSize(context.scrollRequestSize).setScroll("10m").get();
    assertNoFailures(searchScrollResponse);
    assertThat(searchScrollResponse.getHits().getTotalHits(), equalTo((long) context.numDocs));
    assertThat(searchScrollResponse.getHits().getHits().length, equalTo(context.scrollRequestSize));
    int counter = 0;
    for (SearchHit hit : searchScrollResponse.getHits()) {
        assertThat(hit.getSortValues()[0], equalTo(sh.getAt(counter++).getSortValues()[0]));
    }
    int iter = 1;
    String scrollId = searchScrollResponse.getScrollId();
    while (true) {
        searchScrollResponse = client().prepareSearchScroll(scrollId).setScroll("10m").get();
        assertNoFailures(searchScrollResponse);
        assertThat(searchScrollResponse.getHits().getTotalHits(), equalTo((long) context.numDocs));
        if (searchScrollResponse.getHits().getHits().length == 0) {
            break;
        }
        int expectedLength;
        int scrollSlice = ++iter * context.scrollRequestSize;
        if (scrollSlice <= context.numDocs) {
            expectedLength = context.scrollRequestSize;
        } else {
            expectedLength = context.scrollRequestSize - (scrollSlice - context.numDocs);
        }
        assertThat(searchScrollResponse.getHits().getHits().length, equalTo(expectedLength));
        for (SearchHit hit : searchScrollResponse.getHits()) {
            assertThat(hit.getSortValues()[0], equalTo(sh.getAt(counter++).getSortValues()[0]));
        }
        scrollId = searchScrollResponse.getScrollId();
    }
    assertThat(counter, equalTo(context.numDocs));
    clearScroll(scrollId);
}
Also used : SearchHit(org.elasticsearch.search.SearchHit) SearchHits(org.elasticsearch.search.SearchHits) SearchResponse(org.elasticsearch.action.search.SearchResponse)

Example 78 with SearchHits

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.search.SearchHits in project elasticsearch by elastic.

the class RelocationIT method testRelocationWhileIndexingRandom.

@TestLogging("org.elasticsearch.action.bulk:TRACE,org.elasticsearch.action.search:TRACE")
public void testRelocationWhileIndexingRandom() throws Exception {
    int numberOfRelocations = scaledRandomIntBetween(1, rarely() ? 10 : 4);
    int numberOfReplicas = randomBoolean() ? 0 : 1;
    int numberOfNodes = numberOfReplicas == 0 ? 2 : 3;
    logger.info("testRelocationWhileIndexingRandom(numRelocations={}, numberOfReplicas={}, numberOfNodes={})", numberOfRelocations, numberOfReplicas, numberOfNodes);
    String[] nodes = new String[numberOfNodes];
    logger.info("--> starting [node1] ...");
    nodes[0] = internalCluster().startNode();
    logger.info("--> creating test index ...");
    prepareCreate("test", Settings.builder().put("index.number_of_shards", 1).put("index.number_of_replicas", numberOfReplicas)).get();
    for (int i = 2; i <= numberOfNodes; i++) {
        logger.info("--> starting [node{}] ...", i);
        nodes[i - 1] = internalCluster().startNode();
        if (i != numberOfNodes) {
            ClusterHealthResponse healthResponse = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForNodes(Integer.toString(i)).setWaitForGreenStatus().execute().actionGet();
            assertThat(healthResponse.isTimedOut(), equalTo(false));
        }
    }
    int numDocs = scaledRandomIntBetween(200, 2500);
    try (BackgroundIndexer indexer = new BackgroundIndexer("test", "type1", client(), numDocs)) {
        logger.info("--> waiting for {} docs to be indexed ...", numDocs);
        waitForDocs(numDocs, indexer);
        logger.info("--> {} docs indexed", numDocs);
        logger.info("--> starting relocations...");
        // if we have replicas shift those
        int nodeShiftBased = numberOfReplicas;
        for (int i = 0; i < numberOfRelocations; i++) {
            int fromNode = (i % 2);
            int toNode = fromNode == 0 ? 1 : 0;
            fromNode += nodeShiftBased;
            toNode += nodeShiftBased;
            numDocs = scaledRandomIntBetween(200, 1000);
            logger.debug("--> Allow indexer to index [{}] documents", numDocs);
            indexer.continueIndexing(numDocs);
            logger.info("--> START relocate the shard from {} to {}", nodes[fromNode], nodes[toNode]);
            client().admin().cluster().prepareReroute().add(new MoveAllocationCommand("test", 0, nodes[fromNode], nodes[toNode])).get();
            if (rarely()) {
                logger.debug("--> flushing");
                client().admin().indices().prepareFlush().get();
            }
            ClusterHealthResponse clusterHealthResponse = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForNoRelocatingShards(true).setTimeout(ACCEPTABLE_RELOCATION_TIME).execute().actionGet();
            assertThat(clusterHealthResponse.isTimedOut(), equalTo(false));
            indexer.pauseIndexing();
            logger.info("--> DONE relocate the shard from {} to {}", fromNode, toNode);
        }
        logger.info("--> done relocations");
        logger.info("--> waiting for indexing threads to stop ...");
        indexer.stop();
        logger.info("--> indexing threads stopped");
        logger.info("--> refreshing the index");
        client().admin().indices().prepareRefresh("test").execute().actionGet();
        logger.info("--> searching the index");
        boolean ranOnce = false;
        for (int i = 0; i < 10; i++) {
            logger.info("--> START search test round {}", i + 1);
            SearchHits hits = client().prepareSearch("test").setQuery(matchAllQuery()).setSize((int) indexer.totalIndexedDocs()).storedFields().execute().actionGet().getHits();
            ranOnce = true;
            if (hits.getTotalHits() != indexer.totalIndexedDocs()) {
                int[] hitIds = new int[(int) indexer.totalIndexedDocs()];
                for (int hit = 0; hit < indexer.totalIndexedDocs(); hit++) {
                    hitIds[hit] = hit + 1;
                }
                IntHashSet set = IntHashSet.from(hitIds);
                for (SearchHit hit : hits.getHits()) {
                    int id = Integer.parseInt(hit.getId());
                    if (!set.remove(id)) {
                        logger.error("Extra id [{}]", id);
                    }
                }
                set.forEach((IntProcedure) value -> {
                    logger.error("Missing id [{}]", value);
                });
            }
            assertThat(hits.getTotalHits(), equalTo(indexer.totalIndexedDocs()));
            logger.info("--> DONE search test round {}", i + 1);
        }
        if (!ranOnce) {
            fail();
        }
    }
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) Arrays(java.util.Arrays) TransportRequest(org.elasticsearch.transport.TransportRequest) Nullable(org.elasticsearch.common.Nullable) SearchHits(org.elasticsearch.search.SearchHits) Matchers.not(org.hamcrest.Matchers.not) IndexStats(org.elasticsearch.action.admin.indices.stats.IndexStats) MoveAllocationCommand(org.elasticsearch.cluster.routing.allocation.command.MoveAllocationCommand) SeqNoStats(org.elasticsearch.index.seqno.SeqNoStats) ClusterState(org.elasticsearch.cluster.ClusterState) Settings(org.elasticsearch.common.settings.Settings) Scope(org.elasticsearch.test.ESIntegTestCase.Scope) SearchResponse(org.elasticsearch.action.search.SearchResponse) Path(java.nio.file.Path) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) SearchHit(org.elasticsearch.search.SearchHit) MockIndexEventListener(org.elasticsearch.test.MockIndexEventListener) Priority(org.elasticsearch.common.Priority) PeerRecoveryTargetService(org.elasticsearch.indices.recovery.PeerRecoveryTargetService) Transport(org.elasticsearch.transport.Transport) TestLogging(org.elasticsearch.test.junit.annotations.TestLogging) Collection(java.util.Collection) RecoveryFileChunkRequest(org.elasticsearch.indices.recovery.RecoveryFileChunkRequest) ElasticsearchAssertions.assertHitCount(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount) Matchers.startsWith(org.hamcrest.Matchers.startsWith) ElasticsearchAssertions.assertSearchHits(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchHits) FileVisitResult(java.nio.file.FileVisitResult) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Stream(java.util.stream.Stream) IndexRequestBuilder(org.elasticsearch.action.index.IndexRequestBuilder) ESIntegTestCase(org.elasticsearch.test.ESIntegTestCase) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) INDEX_SEQ_NO_CHECKPOINT_SYNC_INTERVAL(org.elasticsearch.index.IndexSettings.INDEX_SEQ_NO_CHECKPOINT_SYNC_INTERVAL) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Optional(java.util.Optional) TransportRequestOptions(org.elasticsearch.transport.TransportRequestOptions) IntProcedure(com.carrotsearch.hppc.procedures.IntProcedure) XContentType(org.elasticsearch.common.xcontent.XContentType) IndexShardStats(org.elasticsearch.action.admin.indices.stats.IndexShardStats) ClusterService(org.elasticsearch.cluster.service.ClusterService) ShardRoutingState(org.elasticsearch.cluster.routing.ShardRoutingState) ArrayList(java.util.ArrayList) IndicesStatsResponse(org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) SequenceNumbersService(org.elasticsearch.index.seqno.SequenceNumbersService) ShardStats(org.elasticsearch.action.admin.indices.stats.ShardStats) TimeValue(org.elasticsearch.common.unit.TimeValue) MockTransportService(org.elasticsearch.test.transport.MockTransportService) TransportService(org.elasticsearch.transport.TransportService) EnableAllocationDecider(org.elasticsearch.cluster.routing.allocation.decider.EnableAllocationDecider) ClusterScope(org.elasticsearch.test.ESIntegTestCase.ClusterScope) IndexShardState(org.elasticsearch.index.shard.IndexShardState) QueryBuilders.matchAllQuery(org.elasticsearch.index.query.QueryBuilders.matchAllQuery) IndexEventListener(org.elasticsearch.index.shard.IndexEventListener) Files(java.nio.file.Files) Semaphore(java.util.concurrent.Semaphore) Client(org.elasticsearch.client.Client) IndexShard(org.elasticsearch.index.shard.IndexShard) IntHashSet(com.carrotsearch.hppc.IntHashSet) IndexFileNames(org.apache.lucene.index.IndexFileNames) Plugin(org.elasticsearch.plugins.Plugin) BackgroundIndexer(org.elasticsearch.test.BackgroundIndexer) ClusterHealthResponse(org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse) IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) NodeEnvironment(org.elasticsearch.env.NodeEnvironment) English(org.apache.lucene.util.English) ElasticsearchAssertions.assertAcked(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked) ElasticsearchAssertions.assertNoFailures(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures) ClusterHealthResponse(org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse) BackgroundIndexer(org.elasticsearch.test.BackgroundIndexer) SearchHit(org.elasticsearch.search.SearchHit) MoveAllocationCommand(org.elasticsearch.cluster.routing.allocation.command.MoveAllocationCommand) IntHashSet(com.carrotsearch.hppc.IntHashSet) SearchHits(org.elasticsearch.search.SearchHits) ElasticsearchAssertions.assertSearchHits(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchHits) TestLogging(org.elasticsearch.test.junit.annotations.TestLogging)

Example 79 with SearchHits

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.search.SearchHits in project elasticsearch by elastic.

the class MultiMatchQueryIT method assertEquivalent.

private static void assertEquivalent(String query, SearchResponse left, SearchResponse right) {
    assertNoFailures(left);
    assertNoFailures(right);
    SearchHits leftHits = left.getHits();
    SearchHits rightHits = right.getHits();
    assertThat(leftHits.getTotalHits(), equalTo(rightHits.getTotalHits()));
    assertThat(leftHits.getHits().length, equalTo(rightHits.getHits().length));
    SearchHit[] hits = leftHits.getHits();
    SearchHit[] rHits = rightHits.getHits();
    for (int i = 0; i < hits.length; i++) {
        assertThat("query: " + query + " hit: " + i, (double) hits[i].getScore(), closeTo(rHits[i].getScore(), 0.00001d));
    }
    for (int i = 0; i < hits.length; i++) {
        if (hits[i].getScore() == hits[hits.length - 1].getScore()) {
            // we need to cut off here since this is the tail of the queue and we might not have fetched enough docs
            return;
        }
        assertThat("query: " + query, hits[i].getId(), equalTo(rHits[i].getId()));
    }
}
Also used : SearchHit(org.elasticsearch.search.SearchHit) SearchHits(org.elasticsearch.search.SearchHits) ElasticsearchAssertions.assertSearchHits(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchHits)

Example 80 with SearchHits

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.search.SearchHits in project elasticsearch by elastic.

the class MoreExpressionTests method testParams.

public void testParams() throws Exception {
    createIndex("test");
    ensureGreen("test");
    indexRandom(true, client().prepareIndex("test", "doc", "1").setSource("x", 10), client().prepareIndex("test", "doc", "2").setSource("x", 3), client().prepareIndex("test", "doc", "3").setSource("x", 5));
    // a = int, b = double, c = long
    String script = "doc['x'] * a + b + ((c + doc['x']) > 5000000009 ? 1 : 0)";
    SearchResponse rsp = buildRequest(script, "a", 2, "b", 3.5, "c", 5000000000L).get();
    SearchHits hits = rsp.getHits();
    assertEquals(3, hits.getTotalHits());
    assertEquals(24.5, hits.getAt(0).field("foo").getValue(), 0.0D);
    assertEquals(9.5, hits.getAt(1).field("foo").getValue(), 0.0D);
    assertEquals(13.5, hits.getAt(2).field("foo").getValue(), 0.0D);
}
Also used : SearchHits(org.elasticsearch.search.SearchHits) SearchResponse(org.elasticsearch.action.search.SearchResponse) ElasticsearchAssertions.assertSearchResponse(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse)

Aggregations

SearchHits (org.elasticsearch.search.SearchHits)137 SearchResponse (org.elasticsearch.action.search.SearchResponse)93 SearchHit (org.elasticsearch.search.SearchHit)86 ArrayList (java.util.ArrayList)45 SearchRequestBuilder (org.elasticsearch.action.search.SearchRequestBuilder)27 IOException (java.io.IOException)25 Map (java.util.Map)23 ElasticsearchAssertions.assertSearchResponse (org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse)20 HashMap (java.util.HashMap)19 IndexRequestBuilder (org.elasticsearch.action.index.IndexRequestBuilder)17 SearchRequest (org.elasticsearch.action.search.SearchRequest)16 Terms (org.elasticsearch.search.aggregations.bucket.terms.Terms)16 TopHits (org.elasticsearch.search.aggregations.metrics.tophits.TopHits)15 SearchSourceBuilder (org.elasticsearch.search.builder.SearchSourceBuilder)14 TotalHits (org.apache.lucene.search.TotalHits)12 Test (org.junit.Test)12 ScoreDoc (org.apache.lucene.search.ScoreDoc)11 Text (org.elasticsearch.common.text.Text)11 InnerHitBuilder (org.elasticsearch.index.query.InnerHitBuilder)11 QueryBuilder (org.elasticsearch.index.query.QueryBuilder)10