private ScoreDoc[] GetDocsUnderTree(string path, bool recurse)
        {
            var field = recurse ? "InTree" : "Path";

            var queryContext = SnQueryContext.CreateDefault();
            var snQuery      = SnQuery.Parse($"{field}:'{path.ToLower()}'", null);

            var lq = Compile(snQuery, queryContext); //LucQuery.Parse(String.Format("{0}:'{1}'", field, path.ToLower()));

            using (var readerFrame = LuceneSearchManager.GetIndexReaderFrame())
            {
                var idxReader = readerFrame.IndexReader;
                var searcher  = new IndexSearcher(idxReader);
                var numDocs   = idxReader.NumDocs();
                try
                {
                    var collector = TopScoreDocCollector.Create(numDocs, false);
                    searcher.Search(lq.Query, collector);
                    var topDocs = collector.TopDocs(0, numDocs);
                    return(topDocs.ScoreDocs);
                }
                finally
                {
                    searcher.Close();
                }
            }
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            args = new[] { TestType.Backup.ToString() };

            if (args.Length == 0)
            {
                Console.WriteLine("Missing test type. Expected 'Backup', 'Restore', 'Validity' or 'Cancellation'.");
                return;
            }
            if (!Enum.TryParse <TestType>(args[0], true, out _testType))
            {
                Console.WriteLine("Invalid test type. Expected 'Backup', 'Restore' or 'Validity'.");
                return;
            }

            _serviceIndexDirectory = Path.GetFullPath($"{Environment.CurrentDirectory}\\..\\..\\..\\..\\..\\" +
                                                      //"SenseNet.Search.Lucene29.Centralized.Service\\" +
                                                      "SenseNet.Search.Lucene29.Centralized.GrpcService\\" +
                                                      "bin\\Debug\\netcoreapp3.1\\App_Data\\LocalIndex");
            Console.WriteLine("IndexDirectory of the service: ");
            Console.WriteLine(_serviceIndexDirectory);

            _backupIndexDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data", "IndexBackup");
            Console.WriteLine("Backup directory: ");
            Console.WriteLine(_backupIndexDirectory);

            IConfiguration configuration = new ConfigurationBuilder()
                                           .AddJsonFile("appsettings.json", true, true)
                                           .AddEnvironmentVariables()
                                           .Build();

            //var serviceBinding = new NetTcpBinding { Security = { Mode = SecurityMode.None } };
            //var serviceEndpoint = new EndpointAddress(configuration["sensenet:search:service:address"]);
            //WaitForServiceStarted(serviceBinding, serviceEndpoint);

            var sender = new MessageSenderManager();

            var builder = new RepositoryBuilder()
                          .SetConsole(Console.Out)
                          .UseLogger(new SnFileSystemEventLogger())
                          .UseTracer(new SnFileSystemTracer())
                          .UseConfiguration(configuration)
                          .UseDataProvider(new MsSqlDataProvider(Options.Create(ConnectionStringOptions.GetLegacyConnectionStrings())))
                          .UseSecurityDataProvider(new EFCSecurityDataProvider(sender,
                                                                               Options.Create(new SenseNet.Security.EFCSecurityStore.Configuration.DataOptions()
            {
                ConnectionString = ConnectionStrings.ConnectionString
            }),
                                                                               NullLogger <EFCSecurityDataProvider> .Instance))
                          .UseSecurityMessageProvider(new RabbitMQMessageProvider(sender,
                                                                                  Options.Create(new MessagingOptions()),
                                                                                  Options.Create(new RabbitMqOptions())))
                          .UseLucene29CentralizedSearchEngineWithGrpc(configuration["sensenet:search:service:address"], options =>
            {
                // trust the server in a development environment
                options.HttpClient = new HttpClient(new HttpClientHandler
                {
                    ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true
                });
                options.DisposeHttpClient = true;
            })
                          .StartWorkflowEngine(false)
                          .DisableNodeObservers()
                          .UseTraceCategories(SnTrace.Categories.Select(x => x.Name).ToArray()) as RepositoryBuilder;

            using (Repository.Start(builder))
            {
                Console.WriteLine("CHECK SQL SERVER CONNECTIVITY (query top level nodes):");
                var root = Node.LoadNode(Repository.RootPath);
                foreach (var node in NodeQuery.QueryChildren(Repository.RootPath).Nodes)
                {
                    Console.WriteLine(node.Path);
                }
                Console.WriteLine();

                Console.WriteLine("CHECK SEARCH SERVER CONNECTIVITY (query top level nodes):");
                var queryContext = new SnQueryContext(QuerySettings.AdminSettings, User.Current.Id);
                var result       = SnQuery.Query("InFolder:/Root", queryContext);
                foreach (var id in result.Hits)
                {
                    Console.WriteLine(NodeHead.Get(id).Path);
                }
                Console.WriteLine();

                SnTrace.EnableAll();

                var engine = (ILuceneIndexingEngine)Providers.Instance.SearchEngine.IndexingEngine;
                switch (_testType)
                {
                case TestType.Backup:
                    new ContinuousIndexTest(engine).RunAsync(CancellationToken.None)
                    .ConfigureAwait(false).GetAwaiter().GetResult();
                    break;

                case TestType.Restore:
                    new RestoreTest(engine).RunAsync(CancellationToken.None)
                    .ConfigureAwait(false).GetAwaiter().GetResult();
                    break;

                case TestType.Validity:
                    new ValidityTest(engine).RunAsync(CancellationToken.None)
                    .ConfigureAwait(false).GetAwaiter().GetResult();
                    break;

                case TestType.Cancellation:
                    new CancellationTest(engine).RunAsync(CancellationToken.None)
                    .ConfigureAwait(false).GetAwaiter().GetResult();
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                // Shut down the service to leave the index.
                IndexManager.IndexingEngine.ShutDownAsync(CancellationToken.None)
                .ConfigureAwait(false).GetAwaiter().GetResult();
            }
        }
Beispiel #3
0
        public virtual TResult Execute <TResult>(Expression expression)
        {
            var count = 0;

            // in case there is a predefined list of nodes, we do not execute a query (but we still need to build it)
            if (!this.ExecuteQuery)
            {
                count = ChildrenDefinition.BaseCollection.Count();
            }

            var query = SnExpression.BuildQuery(expression, typeof(T), this.ContextPath, this.ChildrenDefinition, out var elementSelection);

            if (TracingEnabled)
            {
                TraceLog.Append("Expression: ").AppendLine(expression.ToString());
                TraceLog.Append("Query:      ").AppendLine(query.ToString());
                TraceLog.AppendLine("--------------");
            }
            var result = this.ExecuteQuery ? query.Execute(SnQueryContext.CreateDefault()) : null;

            if (query.CountOnly)
            {
                if (this.ExecuteQuery)
                {
                    count = result.TotalCount;
                }

                if (query.ExistenceOnly)
                {
                    return((TResult)Convert.ChangeType(count > 0, typeof(TResult)));
                }
                return((TResult)Convert.ChangeType(count, typeof(TResult)));
            }

            if (this.ExecuteQuery)
            {
                count = result.TotalCount;
            }

            if (count == 0)
            {
                if (query.ThrowIfEmpty)
                {
                    if (elementSelection == "elementat")
                    {
                        // ReSharper disable once NotResolvedInText
                        throw new ArgumentOutOfRangeException("Index was out of range.");
                    }
                    else
                    {
                        throw new InvalidOperationException("Sequence contains no elements.");
                    }
                }
                return(default(TResult));
            }

            if (typeof(Node).IsAssignableFrom(typeof(TResult)))
            {
                if (ExecuteQuery)
                {
                    return((TResult)Convert.ChangeType(Node.LoadNode(result.Hits.First()), typeof(TResult)));
                }
                return((TResult)Convert.ChangeType(ChildrenDefinition.BaseCollection.First(), typeof(TResult)));
            }

            switch (elementSelection)
            {
            case "first":
                return(ExecuteQuery
                        ? (TResult)Convert.ChangeType(Content.Load(result.Hits.FirstOrDefault()), typeof(TResult))
                        : (TResult)Convert.ChangeType(Content.Create(ChildrenDefinition.BaseCollection.FirstOrDefault()), typeof(TResult)));

            case "last":
                return(ExecuteQuery
                        ? (TResult)Convert.ChangeType(Content.Load(result.Hits.LastOrDefault()), typeof(TResult))
                        : (TResult)Convert.ChangeType(Content.Create(ChildrenDefinition.BaseCollection.LastOrDefault()), typeof(TResult)));

            case "single":
                return(ExecuteQuery
                        ? (TResult)Convert.ChangeType(Content.Load(result.Hits.SingleOrDefault()), typeof(TResult))
                        : (TResult)Convert.ChangeType(Content.Create(ChildrenDefinition.BaseCollection.SingleOrDefault()), typeof(TResult)));

            case "elementat":
                var any = ExecuteQuery ? result.Hits.Any() : ChildrenDefinition.BaseCollection.Any();
                if (!any)
                {
                    if (query.ThrowIfEmpty)
                    {
                        // ReSharper disable once NotResolvedInText
                        throw new ArgumentOutOfRangeException("Index was out of range.");
                    }
                    else
                    {
                        return(default(TResult));
                    }
                }
                return(ExecuteQuery
                        ? (TResult)Convert.ChangeType(Content.Load(result.Hits.FirstOrDefault()), typeof(TResult))
                        : (TResult)Convert.ChangeType(Content.Create(ChildrenDefinition.BaseCollection.FirstOrDefault()), typeof(TResult)));

            default:
                throw new SnNotSupportedException();
            }
        }