Search in sources :

Example 16 with Entity

use of org.opensearch.ad.model.Entity 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)

Example 17 with Entity

use of org.opensearch.ad.model.Entity in project anomaly-detection by opensearch-project.

the class NoPowermockSearchFeatureDaoTests method testGetHighestCountEntitiesUsingTermsAgg.

@SuppressWarnings("unchecked")
@Test
public void testGetHighestCountEntitiesUsingTermsAgg() {
    SearchHits hits = new SearchHits(new SearchHit[] {}, null, Float.NaN);
    String entity1Name = "value1";
    long entity1Count = 3;
    StringTerms.Bucket entity1Bucket = new StringTerms.Bucket(new BytesRef(entity1Name.getBytes(StandardCharsets.UTF_8), 0, entity1Name.getBytes(StandardCharsets.UTF_8).length), entity1Count, null, false, 0L, DocValueFormat.RAW);
    String entity2Name = "value2";
    long entity2Count = 1;
    StringTerms.Bucket entity2Bucket = new StringTerms.Bucket(new BytesRef(entity2Name.getBytes(StandardCharsets.UTF_8), 0, entity2Name.getBytes(StandardCharsets.UTF_8).length), entity2Count, null, false, 0, DocValueFormat.RAW);
    List<StringTerms.Bucket> stringBuckets = ImmutableList.of(entity1Bucket, entity2Bucket);
    StringTerms termsAgg = new StringTerms(// "term_agg",
    SearchFeatureDao.AGG_NAME_TOP, InternalOrder.key(false), BucketOrder.count(false), 1, 0, Collections.emptyMap(), DocValueFormat.RAW, 1, false, 0, stringBuckets, 0);
    InternalAggregations internalAggregations = InternalAggregations.from(Collections.singletonList(termsAgg));
    SearchResponseSections searchSections = new SearchResponseSections(hits, internalAggregations, null, false, false, null, 1);
    SearchResponse searchResponse = new SearchResponse(searchSections, null, 1, 1, 0, 30, ShardSearchFailure.EMPTY_ARRAY, SearchResponse.Clusters.EMPTY);
    doAnswer(invocation -> {
        SearchRequest request = invocation.getArgument(0);
        assertEquals(1, request.indices().length);
        assertTrue(detector.getIndices().contains(request.indices()[0]));
        AggregatorFactories.Builder aggs = request.source().aggregations();
        assertEquals(1, aggs.count());
        Collection<AggregationBuilder> factory = aggs.getAggregatorFactories();
        assertTrue(!factory.isEmpty());
        assertThat(factory.iterator().next(), instanceOf(TermsAggregationBuilder.class));
        ActionListener<SearchResponse> listener = invocation.getArgument(1);
        listener.onResponse(searchResponse);
        return null;
    }).when(client).search(any(SearchRequest.class), any(ActionListener.class));
    String categoryField = "fieldName";
    when(detector.getCategoryField()).thenReturn(Collections.singletonList(categoryField));
    ActionListener<List<Entity>> listener = mock(ActionListener.class);
    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(2, result.size());
    assertEquals(Entity.createSingleAttributeEntity(categoryField, entity1Name), result.get(0));
    assertEquals(Entity.createSingleAttributeEntity(categoryField, entity2Name), result.get(1));
}
Also used : SearchRequest(org.opensearch.action.search.SearchRequest) Entity(org.opensearch.ad.model.Entity) SearchResponseSections(org.opensearch.action.search.SearchResponseSections) AggregationBuilder(org.opensearch.search.aggregations.AggregationBuilder) TermsAggregationBuilder(org.opensearch.search.aggregations.bucket.terms.TermsAggregationBuilder) SumAggregationBuilder(org.opensearch.search.aggregations.metrics.SumAggregationBuilder) SearchResponse(org.opensearch.action.search.SearchResponse) InternalSearchResponse(org.opensearch.search.internal.InternalSearchResponse) InternalAggregations(org.opensearch.search.aggregations.InternalAggregations) TermsAggregationBuilder(org.opensearch.search.aggregations.bucket.terms.TermsAggregationBuilder) StringTerms(org.opensearch.search.aggregations.bucket.terms.StringTerms) ActionListener(org.opensearch.action.ActionListener) InternalBucket(org.opensearch.search.aggregations.bucket.filter.InternalFilters.InternalBucket) AggregatorFactories(org.opensearch.search.aggregations.AggregatorFactories) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) SearchHits(org.opensearch.search.SearchHits) BytesRef(org.apache.lucene.util.BytesRef) AbstractADTest(org.opensearch.ad.AbstractADTest) Test(org.junit.Test)

Example 18 with Entity

use of org.opensearch.ad.model.Entity in project anomaly-detection by opensearch-project.

the class NoPowermockSearchFeatureDaoTests method testGetHighestCountEntitiesNotEnoughTime.

@SuppressWarnings("unchecked")
public void testGetHighestCountEntitiesNotEnoughTime() throws InterruptedException {
    SearchResponse response1 = createPageResponse(attrs1);
    SearchResponse response2 = createPageResponse(attrs2);
    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(response2);
        }
        return null;
    }).when(client).search(any(), any());
    ActionListener<List<Entity>> listener = mock(ActionListener.class);
    long timeoutMillis = 60_000L;
    searchFeatureDao = new SearchFeatureDao(client, xContentRegistry(), interpolator, clientUtil, settings, clusterService, AnomalyDetectorSettings.NUM_SAMPLES_PER_TREE, clock, 2, 1, timeoutMillis);
    CountDownLatch clockInvoked = new CountDownLatch(2);
    when(clock.millis()).thenAnswer(new Answer<Long>() {

        @Override
        public Long answer(InvocationOnMock invocation) throws Throwable {
            clockInvoked.countDown();
            if (clockInvoked.getCount() == 1) {
                return 1L;
            } else {
                return 2L + timeoutMillis;
            }
        }
    });
    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));
    // exited early due to timeout
    assertEquals(1, inProgress.getCount());
    // first called to create expired time; second called to check if time has expired
    assertTrue(clockInvoked.await(10000L, TimeUnit.MILLISECONDS));
}
Also used : Entity(org.opensearch.ad.model.Entity) CountDownLatch(java.util.concurrent.CountDownLatch) SearchResponse(org.opensearch.action.search.SearchResponse) InternalSearchResponse(org.opensearch.search.internal.InternalSearchResponse) InvocationOnMock(org.mockito.invocation.InvocationOnMock) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList)

Example 19 with Entity

use of org.opensearch.ad.model.Entity in project anomaly-detection by opensearch-project.

the class NoPowermockSearchFeatureDaoTests method testGetHighestCountEntitiesUsingPagination.

@SuppressWarnings("unchecked")
public void testGetHighestCountEntitiesUsingPagination() {
    SearchResponse response1 = createPageResponse(attrs1);
    CountDownLatch inProgress = new CountDownLatch(1);
    doAnswer(invocation -> {
        ActionListener<SearchResponse> listener = invocation.getArgument(1);
        inProgress.countDown();
        listener.onResponse(response1);
        return null;
    }).when(client).search(any(), any());
    ActionListener<List<Entity>> listener = mock(ActionListener.class);
    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));
}
Also used : Entity(org.opensearch.ad.model.Entity) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) CountDownLatch(java.util.concurrent.CountDownLatch) SearchResponse(org.opensearch.action.search.SearchResponse) InternalSearchResponse(org.opensearch.search.internal.InternalSearchResponse)

Example 20 with Entity

use of org.opensearch.ad.model.Entity in project anomaly-detection by opensearch-project.

the class PriorityCacheTests method replaceInOtherCacheSetUp.

private void replaceInOtherCacheSetUp() {
    Entity entity5 = Entity.createSingleAttributeEntity("attributeName1", "attributeVal5");
    Entity entity6 = Entity.createSingleAttributeEntity("attributeName1", "attributeVal6");
    ModelState<EntityModel> modelState5 = new ModelState<>(new EntityModel(entity5, new ArrayDeque<>(), null), entity5.getModelId(detectorId2).get(), detectorId2, ModelType.ENTITY.getName(), clock, 0);
    ModelState<EntityModel> modelState6 = new ModelState<>(new EntityModel(entity6, new ArrayDeque<>(), null), entity6.getModelId(detectorId2).get(), detectorId2, ModelType.ENTITY.getName(), clock, 0);
    for (int i = 0; i < 3; i++) {
        // bypass doorkeeper and leave room for lower frequency entity in testSelectToCold
        cacheProvider.get(entity5.getModelId(detectorId2).get(), detector2);
        cacheProvider.get(entity6.getModelId(detectorId2).get(), detector2);
    }
    for (int i = 0; i < 10; i++) {
        // entity1 cannot replace entity2 due to frequency
        cacheProvider.get(entity2.getModelId(detectorId).get(), detector);
    }
    // put modelState5 in dedicated and modelState6 in shared cache
    when(memoryTracker.canAllocate(anyLong())).thenReturn(true);
    cacheProvider.hostIfPossible(detector2, modelState5);
    cacheProvider.hostIfPossible(detector2, modelState6);
    // fill in dedicated cache
    cacheProvider.hostIfPossible(detector, modelState2);
    // don't allow to use shared cache afterwards
    when(memoryTracker.canAllocate(anyLong())).thenReturn(false);
}
Also used : Entity(org.opensearch.ad.model.Entity) EntityModel(org.opensearch.ad.ml.EntityModel) ModelState(org.opensearch.ad.ml.ModelState) ArrayDeque(java.util.ArrayDeque)

Aggregations

Entity (org.opensearch.ad.model.Entity)66 ActionListener (org.opensearch.action.ActionListener)37 ArrayList (java.util.ArrayList)36 List (java.util.List)35 AnomalyDetector (org.opensearch.ad.model.AnomalyDetector)34 Client (org.opensearch.client.Client)31 Optional (java.util.Optional)30 SearchRequest (org.opensearch.action.search.SearchRequest)30 HashMap (java.util.HashMap)29 Map (java.util.Map)28 IOException (java.io.IOException)26 LogManager (org.apache.logging.log4j.LogManager)26 Logger (org.apache.logging.log4j.Logger)26 SearchResponse (org.opensearch.action.search.SearchResponse)25 Settings (org.opensearch.common.settings.Settings)23 Set (java.util.Set)22 GetRequest (org.opensearch.action.get.GetRequest)22 ANOMALY_DETECTORS_INDEX (org.opensearch.ad.model.AnomalyDetector.ANOMALY_DETECTORS_INDEX)22 AnomalyDetectorJob (org.opensearch.ad.model.AnomalyDetectorJob)22 AnomalyDetectionException (org.opensearch.ad.common.exception.AnomalyDetectionException)21