private IRepositoryQuery GetSystemFilterQuery(IQueryVisitorContext context)
        {
            var builderContext    = context as IQueryBuilderContext;
            var systemFilter      = builderContext?.Source.GetSystemFilter();
            var systemFilterQuery = systemFilter?.GetQuery().Clone();

            if (systemFilterQuery == null)
            {
                systemFilterQuery = new RepositoryQuery <Stack>();
                foreach (var range in builderContext?.Source.GetDateRanges() ?? Enumerable.Empty <DateRange>())
                {
                    systemFilterQuery.DateRange(range.StartDate, range.EndDate, range.Field, range.TimeZone);
                }
            }

            if (!systemFilterQuery.HasAppFilter())
            {
                systemFilterQuery.AppFilter(builderContext?.Source.GetAppFilter());
            }

            foreach (var range in systemFilterQuery.GetDateRanges() ?? Enumerable.Empty <DateRange>())
            {
                if (range.Field == _inferredEventDateField || range.Field == "date")
                {
                    range.Field = _inferredStackLastOccurrenceField;
                }
            }

            return(systemFilterQuery);
        }
        public Task <long> RemoveAllAsync(string organizationId, string clientIpAddress, DateTime?utcStart, DateTime?utcEnd, CommandOptionsDescriptor <PersistentEvent> options = null)
        {
            if (String.IsNullOrEmpty(organizationId))
            {
                throw new ArgumentNullException(nameof(organizationId));
            }

            var query = new RepositoryQuery <PersistentEvent>().Organization(organizationId);

            if (utcStart.HasValue && utcEnd.HasValue)
            {
                query = query.DateRange(utcStart, utcEnd, InferField(e => e.Date)).Index(utcStart, utcEnd);
            }
            else if (utcEnd.HasValue)
            {
                query = query.ElasticFilter(Query <PersistentEvent> .DateRange(r => r.Field(e => e.Date).LessThan(utcEnd)));
            }
            else if (utcStart.HasValue)
            {
                query = query.ElasticFilter(Query <PersistentEvent> .DateRange(r => r.Field(e => e.Date).GreaterThan(utcStart)));
            }

            if (!String.IsNullOrEmpty(clientIpAddress))
            {
                query = query.FieldEquals(EventIndex.Alias.IpAddress, clientIpAddress);
            }

            return(RemoveAllAsync(q => query, options));
        }