Search in sources :

Example 31 with ClusterService

use of org.opensearch.cluster.service.ClusterService in project k-NN by opensearch-project.

the class VectorReaderTests method testRead_valid_incompleteIndex.

public void testRead_valid_incompleteIndex() throws InterruptedException, ExecutionException, IOException {
    // Check if we get the right number of vectors if the index contains docs that are missing fields
    // Create an index with knn disabled
    String indexName = "test-index";
    String fieldName = "test-field";
    int dim = 16;
    int numVectors = 100;
    createIndex(indexName);
    // Add a field mapping to the index
    createKnnIndexMapping(indexName, fieldName, dim);
    // Create list of random vectors and ingest
    Random random = new Random();
    List<Float[]> vectors = new ArrayList<>();
    for (int i = 0; i < numVectors; i++) {
        Float[] vector = new Float[dim];
        for (int j = 0; j < dim; j++) {
            vector[j] = random.nextFloat();
        }
        vectors.add(vector);
        addKnnDoc(indexName, Integer.toString(i), fieldName, vector);
    }
    // Create documents that do not have fieldName for training
    int docsWithoutKNN = 100;
    String fieldNameWithoutKnn = "test-field-2";
    for (int i = 0; i < docsWithoutKNN; i++) {
        addDoc(indexName, Integer.toString(i + numVectors), fieldNameWithoutKnn, "dummyValue");
    }
    // Configure VectorReader
    ClusterService clusterService = node().injector().getInstance(ClusterService.class);
    VectorReader vectorReader = new VectorReader(client());
    // Read all vectors and confirm they match vectors
    TestVectorConsumer testVectorConsumer = new TestVectorConsumer();
    final CountDownLatch inProgressLatch1 = new CountDownLatch(1);
    vectorReader.read(clusterService, indexName, fieldName, 10000, 10, testVectorConsumer, ActionListener.wrap(response -> inProgressLatch1.countDown(), e -> fail(e.toString())));
    assertTrue(inProgressLatch1.await(100, TimeUnit.SECONDS));
    List<Float[]> consumedVectors = testVectorConsumer.getVectorsConsumed();
    assertEquals(numVectors, consumedVectors.size());
    List<Float> flatVectors = vectors.stream().flatMap(Arrays::stream).collect(Collectors.toList());
    List<Float> flatConsumedVectors = consumedVectors.stream().flatMap(Arrays::stream).collect(Collectors.toList());
    assertEquals(new HashSet<>(flatVectors), new HashSet<>(flatConsumedVectors));
}
Also used : Arrays(java.util.Arrays) IOException(java.io.IOException) Random(java.util.Random) Collectors(java.util.stream.Collectors) ValidationException(org.opensearch.common.ValidationException) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Logger(org.apache.logging.log4j.Logger) ClusterService(org.opensearch.cluster.service.ClusterService) KNNSingleNodeTestCase(org.opensearch.knn.KNNSingleNodeTestCase) ActionListener(org.opensearch.action.ActionListener) LogManager(org.apache.logging.log4j.LogManager) ArrayList(java.util.ArrayList) CountDownLatch(java.util.concurrent.CountDownLatch) ClusterService(org.opensearch.cluster.service.ClusterService) Random(java.util.Random)

Example 32 with ClusterService

use of org.opensearch.cluster.service.ClusterService in project k-NN by opensearch-project.

the class VectorReaderTests method testRead_invalid_searchSize.

public void testRead_invalid_searchSize() {
    // Create the index
    String indexName = "test-index";
    String fieldName = "test-field";
    int dim = 16;
    createIndex(indexName);
    // Add a field mapping to the index
    createKnnIndexMapping(indexName, fieldName, dim);
    // Configure VectorReader
    ClusterService clusterService = node().injector().getInstance(ClusterService.class);
    VectorReader vectorReader = new VectorReader(client());
    // Search size is negative
    expectThrows(ValidationException.class, () -> vectorReader.read(clusterService, indexName, fieldName, 100, -10, null, null));
    // Search size is greater than 10000
    expectThrows(ValidationException.class, () -> vectorReader.read(clusterService, indexName, fieldName, 100, 20000, null, null));
}
Also used : ClusterService(org.opensearch.cluster.service.ClusterService)

Example 33 with ClusterService

use of org.opensearch.cluster.service.ClusterService in project k-NN by opensearch-project.

the class VectorReaderTests method testRead_valid_OnlyGetMaxVectors.

public void testRead_valid_OnlyGetMaxVectors() throws InterruptedException, ExecutionException, IOException {
    // Check if we can limit the number of docs via max operation
    // Create an index with knn disabled
    String indexName = "test-index";
    String fieldName = "test-field";
    int dim = 16;
    int numVectorsIndex = 100;
    int maxNumVectorsRead = 20;
    createIndex(indexName);
    // Add a field mapping to the index
    createKnnIndexMapping(indexName, fieldName, dim);
    // Create list of random vectors and ingest
    Random random = new Random();
    for (int i = 0; i < numVectorsIndex; i++) {
        Float[] vector = new Float[dim];
        for (int j = 0; j < dim; j++) {
            vector[j] = random.nextFloat();
        }
        addKnnDoc(indexName, Integer.toString(i), fieldName, vector);
    }
    // Configure VectorReader
    ClusterService clusterService = node().injector().getInstance(ClusterService.class);
    VectorReader vectorReader = new VectorReader(client());
    // Read maxNumVectorsRead vectors
    TestVectorConsumer testVectorConsumer = new TestVectorConsumer();
    final CountDownLatch inProgressLatch1 = new CountDownLatch(1);
    vectorReader.read(clusterService, indexName, fieldName, maxNumVectorsRead, 10, testVectorConsumer, ActionListener.wrap(response -> inProgressLatch1.countDown(), e -> fail(e.toString())));
    assertTrue(inProgressLatch1.await(100, TimeUnit.SECONDS));
    List<Float[]> consumedVectors = testVectorConsumer.getVectorsConsumed();
    assertEquals(maxNumVectorsRead, consumedVectors.size());
}
Also used : Arrays(java.util.Arrays) IOException(java.io.IOException) Random(java.util.Random) Collectors(java.util.stream.Collectors) ValidationException(org.opensearch.common.ValidationException) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Logger(org.apache.logging.log4j.Logger) ClusterService(org.opensearch.cluster.service.ClusterService) KNNSingleNodeTestCase(org.opensearch.knn.KNNSingleNodeTestCase) ActionListener(org.opensearch.action.ActionListener) LogManager(org.apache.logging.log4j.LogManager) ClusterService(org.opensearch.cluster.service.ClusterService) Random(java.util.Random) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 34 with ClusterService

use of org.opensearch.cluster.service.ClusterService in project k-NN by opensearch-project.

the class VectorReaderTests method testRead_invalid_indexDoesNotExist.

public void testRead_invalid_indexDoesNotExist() {
    // Check that read throws a validation exception when the index does not exist
    String indexName = "test-index";
    String fieldName = "test-field";
    // Configure VectorReader
    ClusterService clusterService = node().injector().getInstance(ClusterService.class);
    VectorReader vectorReader = new VectorReader(client());
    // Should throw a validation exception because index does not exist
    expectThrows(ValidationException.class, () -> vectorReader.read(clusterService, indexName, fieldName, 10000, 10, null, null));
}
Also used : ClusterService(org.opensearch.cluster.service.ClusterService)

Example 35 with ClusterService

use of org.opensearch.cluster.service.ClusterService in project anomaly-detection by opensearch-project.

the class NoPowermockSearchFeatureDaoTests method testGetHighestCountEntitiesExhaustedPages.

@SuppressWarnings("unchecked")
public void testGetHighestCountEntitiesExhaustedPages() throws InterruptedException {
    SearchResponse response1 = createPageResponse(attrs1);
    CompositeAggregation emptyComposite = mock(CompositeAggregation.class);
    when(emptyComposite.getName()).thenReturn(SearchFeatureDao.AGG_NAME_TOP);
    when(emptyComposite.afterKey()).thenReturn(null);
    // empty bucket
    when(emptyComposite.getBuckets()).thenAnswer((Answer<List<CompositeAggregation.Bucket>>) invocation -> {
        return new ArrayList<CompositeAggregation.Bucket>();
    });
    Aggregations emptyAggs = new Aggregations(Collections.singletonList(emptyComposite));
    SearchResponseSections emptySections = new SearchResponseSections(SearchHits.empty(), emptyAggs, null, false, null, null, 1);
    SearchResponse emptyResponse = new SearchResponse(emptySections, null, 1, 1, 0, 0, ShardSearchFailure.EMPTY_ARRAY, Clusters.EMPTY);
    CountDownLatch inProgress = new CountDownLatch(2);
    doAnswer(invocation -> {
        ActionListener<SearchResponse> listener = invocation.getArgument(1);
        inProgress.countDown();
        if (inProgress.getCount() == 1) {
            listener.onResponse(response1);
        } else {
            listener.onResponse(emptyResponse);
        }
        return null;
    }).when(client).search(any(), any());
    ActionListener<List<Entity>> listener = mock(ActionListener.class);
    searchFeatureDao = new SearchFeatureDao(client, xContentRegistry(), interpolator, clientUtil, settings, clusterService, AnomalyDetectorSettings.NUM_SAMPLES_PER_TREE, clock, 2, 1, 60_000L);
    searchFeatureDao.getHighestCountEntities(detector, 10L, 20L, listener);
    ArgumentCaptor<List<Entity>> captor = ArgumentCaptor.forClass(List.class);
    verify(listener).onResponse(captor.capture());
    List<Entity> result = captor.getValue();
    assertEquals(1, result.size());
    assertEquals(Entity.createEntityByReordering(attrs1), result.get(0));
    // both counts are used in client.search
    assertTrue(inProgress.await(10000L, TimeUnit.MILLISECONDS));
}
Also used : Arrays(java.util.Arrays) IsInstanceOf.instanceOf(org.hamcrest.core.IsInstanceOf.instanceOf) NoneCircuitBreakerService(org.opensearch.indices.breaker.NoneCircuitBreakerService) AbstractADTest(org.opensearch.ad.AbstractADTest) Releasables(org.opensearch.common.lease.Releasables) AggregationBuilder(org.opensearch.search.aggregations.AggregationBuilder) InternalMax(org.opensearch.search.aggregations.metrics.InternalMax) MockBigArrays(org.opensearch.common.util.MockBigArrays) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Map(java.util.Map) SingleFeatureLinearUniformInterpolator(org.opensearch.ad.dataprocessor.SingleFeatureLinearUniformInterpolator) InternalAggregations(org.opensearch.search.aggregations.InternalAggregations) ZoneOffset(java.time.ZoneOffset) ActionListener(org.opensearch.action.ActionListener) MockPageCacheRecycler(org.opensearch.common.util.MockPageCacheRecycler) DateFormatter(org.opensearch.common.time.DateFormatter) Client(org.opensearch.client.Client) HyperLogLogPlusPlus(org.opensearch.search.aggregations.metrics.HyperLogLogPlusPlus) Clusters(org.opensearch.action.search.SearchResponse.Clusters) BytesRef(org.apache.lucene.util.BytesRef) SearchHit(org.opensearch.search.SearchHit) Collection(java.util.Collection) Feature(org.opensearch.ad.model.Feature) Settings(org.opensearch.common.settings.Settings) StandardCharsets(java.nio.charset.StandardCharsets) InvocationTargetException(java.lang.reflect.InvocationTargetException) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) LinearUniformInterpolator(org.opensearch.ad.dataprocessor.LinearUniformInterpolator) Logger(org.apache.logging.log4j.Logger) TestHelpers(org.opensearch.ad.TestHelpers) Entry(java.util.Map.Entry) Optional(java.util.Optional) Mockito.mock(org.mockito.Mockito.mock) InternalDateRange(org.opensearch.search.aggregations.bucket.range.InternalDateRange) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BucketOrder(org.opensearch.search.aggregations.BucketOrder) InternalFilter(org.opensearch.search.aggregations.bucket.filter.InternalFilter) StringTerms(org.opensearch.search.aggregations.bucket.terms.StringTerms) DocValueFormat(org.opensearch.search.DocValueFormat) AggregatorFactories(org.opensearch.search.aggregations.AggregatorFactories) HashMap(java.util.HashMap) Aggregations(org.opensearch.search.aggregations.Aggregations) AbstractHyperLogLogPlusPlus(org.opensearch.search.aggregations.metrics.AbstractHyperLogLogPlusPlus) SearchHits(org.opensearch.search.SearchHits) SimpleImmutableEntry(java.util.AbstractMap.SimpleImmutableEntry) BitMixer(com.carrotsearch.hppc.BitMixer) Constructor(java.lang.reflect.Constructor) AnomalyDetectorSettings(org.opensearch.ad.settings.AnomalyDetectorSettings) InternalOrder(org.opensearch.search.aggregations.InternalOrder) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ArgumentCaptor(org.mockito.ArgumentCaptor) ImmutableList(com.google.common.collect.ImmutableList) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) SearchRequest(org.opensearch.action.search.SearchRequest) SearchResponse(org.opensearch.action.search.SearchResponse) ClusterSettings(org.opensearch.common.settings.ClusterSettings) InternalCardinality(org.opensearch.search.aggregations.metrics.InternalCardinality) QueryBuilders(org.opensearch.index.query.QueryBuilders) AbstractHyperLogLog(org.opensearch.search.aggregations.metrics.AbstractHyperLogLog) ClientUtil(org.opensearch.ad.util.ClientUtil) IOException(java.io.IOException) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) CompositeAggregation(org.opensearch.search.aggregations.bucket.composite.CompositeAggregation) InternalSearchResponse(org.opensearch.search.internal.InternalSearchResponse) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) TotalHits(org.apache.lucene.search.TotalHits) InternalFilters(org.opensearch.search.aggregations.bucket.filter.InternalFilters) ChronoUnit(java.time.temporal.ChronoUnit) Entity(org.opensearch.ad.model.Entity) SearchResponseSections(org.opensearch.action.search.SearchResponseSections) DateFieldMapper(org.opensearch.index.mapper.DateFieldMapper) TermsAggregationBuilder(org.opensearch.search.aggregations.bucket.terms.TermsAggregationBuilder) ShardSearchFailure(org.opensearch.action.search.ShardSearchFailure) InternalBucket(org.opensearch.search.aggregations.bucket.filter.InternalFilters.InternalBucket) ClusterService(org.opensearch.cluster.service.ClusterService) Clock(java.time.Clock) IntervalTimeConfiguration(org.opensearch.ad.model.IntervalTimeConfiguration) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) SumAggregationBuilder(org.opensearch.search.aggregations.metrics.SumAggregationBuilder) Entity(org.opensearch.ad.model.Entity) CompositeAggregation(org.opensearch.search.aggregations.bucket.composite.CompositeAggregation) SearchResponseSections(org.opensearch.action.search.SearchResponseSections) InternalAggregations(org.opensearch.search.aggregations.InternalAggregations) Aggregations(org.opensearch.search.aggregations.Aggregations) CountDownLatch(java.util.concurrent.CountDownLatch) SearchResponse(org.opensearch.action.search.SearchResponse) InternalSearchResponse(org.opensearch.search.internal.InternalSearchResponse) InternalBucket(org.opensearch.search.aggregations.bucket.filter.InternalFilters.InternalBucket) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList)

Aggregations

ClusterService (org.opensearch.cluster.service.ClusterService)296 ThreadPool (org.opensearch.threadpool.ThreadPool)123 Settings (org.opensearch.common.settings.Settings)115 ClusterState (org.opensearch.cluster.ClusterState)106 DiscoveryNode (org.opensearch.cluster.node.DiscoveryNode)103 TestThreadPool (org.opensearch.threadpool.TestThreadPool)93 TransportService (org.opensearch.transport.TransportService)86 ClusterSettings (org.opensearch.common.settings.ClusterSettings)76 ActionListener (org.opensearch.action.ActionListener)75 Before (org.junit.Before)66 ActionFilters (org.opensearch.action.support.ActionFilters)66 CountDownLatch (java.util.concurrent.CountDownLatch)65 HashSet (java.util.HashSet)63 TimeValue (org.opensearch.common.unit.TimeValue)61 IOException (java.io.IOException)56 IndexMetadata (org.opensearch.cluster.metadata.IndexMetadata)53 OpenSearchTestCase (org.opensearch.test.OpenSearchTestCase)48 Collections (java.util.Collections)47 ClusterName (org.opensearch.cluster.ClusterName)47 Metadata (org.opensearch.cluster.metadata.Metadata)47