Ejemplo n.º 1
0
 public SearchResult <T> Search(ISearchQuery query)
 {
     using (ConnectionScope.Enter())
     {
         return(_baseDA.Search(query));
     }
 }
Ejemplo n.º 2
0
        public async Task <ISearchResult> SearchQueryAsync(string indexName, ISearchQuery query, SearchOptions?options = default)
        {
            options ??= new SearchOptions();
            options.TimeoutValue ??= _context.ClusterOptions.SearchTimeout;

            ThrowIfNotBootstrapped();

            var searchRequest = new SearchRequest
            {
                Index   = indexName,
                Query   = query,
                Options = options,
                Token   = options.Token,
                Timeout = options.TimeoutValue.Value
            };

            async Task <ISearchResult> Func()
            {
                var client1  = LazySearchClient.Value;
                var request1 = searchRequest;

                return(await client1.QueryAsync(request1, request1.Token).ConfigureAwait(false));
            }

            return(await _retryOrchestrator.RetryAsync(Func, searchRequest).ConfigureAwait(false));
        }
Ejemplo n.º 3
0
        private void LoadBusinessObjects(ISearchQuery query)
        {
            try
            {
                var srv = new DataLoadingService {
                    Repository = Repository
                };

                srv.ProgressChanged += (sender, tuple) =>
                {
                    SetProgress(tuple);
                    if (tuple.Item3 != null)
                    {
                        BusinessObjectList.Add(tuple.Item3 as BusinessObject);
                    }
                };
                srv.Finished += (sender, isSucceed) =>
                {
                    if (!isSucceed)
                    {
                        AlertError(srv.Error);
                    }
                    ResetProgress();
                };

                BusinessObjectList.Clear();
                srv.Execute(query);
            }
            catch (Exception ex)
            {
                AlertError(ex.Message);
            }
        }
Ejemplo n.º 4
0
 public void MinusPreceededByLetterInWantedTreatedLiterally()
 {
     _searchQuery = new SearchQuery("cat-dog");
     Assert.AreEqual(0, _searchQuery.UnwantedAtoms.Count);
     Assert.AreEqual(1, _searchQuery.WantedAtoms.Count);
     Assert.AreEqual("cat-dog", _searchQuery.WantedAtoms[0]);
 }
Ejemplo n.º 5
0
        /// <inheritdoc />
        public virtual async Task <List <T> > SearchAsync <T>(Wallet wallet, ISearchQuery query, SearchOptions options, int count, int skip)
            where T : RecordBase, new()
        {
            using (var search = await NonSecrets.OpenSearchAsync(wallet, new T().TypeName,
                                                                 (query ?? SearchQuery.Empty).ToJson(),
                                                                 (options ?? new SearchOptions()).ToJson()))
            {
                if (skip > 0)
                {
                    await search.NextAsync(wallet, skip);
                }
                var result = JsonConvert.DeserializeObject <SearchResult>(await search.NextAsync(wallet, count), _jsonSettings);

                return(result.Records?
                       .Select(x =>
                {
                    var record = JsonConvert.DeserializeObject <T>(x.Value, _jsonSettings);
                    foreach (var tag in x.Tags)
                    {
                        record.Tags[tag.Key] = tag.Value;
                    }
                    return record;
                })
                       .ToList()
                       ?? new List <T>());
            }
        }
Ejemplo n.º 6
0
        public static string GetSql(ISearchQuery searchQuery)
        {
            var tagFilter        = string.Empty;
            var selectedTagCount = searchQuery.SelectedTags.Count;

            if (selectedTagCount > 0)
            {
                for (var i = 0; i < selectedTagCount; i++)
                {
                    tagFilter +=
                        $"JOIN Tag AS tag{i} ON BusinessObject.id = tag{i}.business_object AND tag{i}.content = '{searchQuery.SelectedTags[i].Text}' ";
                }
            }

            var textFilterSql = "";

            if (!string.IsNullOrEmpty(searchQuery.TextQuery))
            {
                textFilterSql =
                    $"WHERE (name LIKE '%{searchQuery.TextQuery}%' OR data LIKE '%{searchQuery.TextQuery}%')";
            }

            var sql =
                $"SELECT id, name FROM BusinessObject {tagFilter} {textFilterSql}";

            var commonTableExpression = $"WITH {TableName}(id, name) AS ({sql})";

            return(commonTableExpression);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Highlights chosen terms in a text, extracting the most relevant sections.
        /// </summary>
        /// <param name="input">Text to highlight terms in.</param>
        /// <param name="fieldName">Name of the field to highlight.</param>
        /// <param name="query">Search query.</param>
        /// <param name="engine">Search engine. Use <c>null</c> to fallback to simple string highlighting method.</param>
        /// <param name="preMatch">Pre matching HTML.</param>
        /// <param name="postMatch">Post matching HTML.</param>
        /// <returns>Highlighted text fragments.</returns>
        public string Highlight(
            string input,
            string fieldName,
            ISearchQuery query,
            ISearchEngine engine = null,
            string preMatch      = "<strong>",
            string postMatch     = "</strong>")
        {
            Guard.NotEmpty(fieldName, nameof(fieldName));

            if (query?.Term == null || input.IsEmpty())
            {
                return(input);
            }

            string hilite = null;

            if (engine != null)
            {
                try
                {
                    hilite = engine.Highlight(input, fieldName, preMatch, postMatch);
                }
                catch { }
            }

            if (hilite.HasValue())
            {
                return(hilite);
            }

            return(input.HighlightKeywords(query.Term, preMatch, postMatch));
        }
Ejemplo n.º 8
0
 /// <summary>
 /// Search domains by Search Query (paging, sorting)
 /// </summary>
 /// <param name="query"></param>
 /// <returns></returns>
 public SearchResult <T> Search(ISearchQuery query)
 {
     using (ConnectionScope.Enter())
     {
         return(Search(query, null));
     }
 }
Ejemplo n.º 9
0
        /// <summary>
        /// Fetches the response from the cache if available.
        /// </summary>
        /// <param name="query">The query.</param>
        /// <returns>
        /// The response if available, or <c>null</c> otherwise
        /// </returns>
        public string FetchCachedResponse(ISearchQuery query)
        {
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }

            // Get the filename the response would've been cached as
            var filename = BuildCacheFilename(query);

            // If the file's not there, it's not cached
            if (!File.Exists(filename))
            {
                return(null);
            }

            // If the file's too old, it's not cached. (No point deleting it though, as it's about to get updated.)
            if (File.GetLastWriteTimeUtc(filename) < this.cacheThreshold)
            {
                return(null);
            }

            // We have a new enough file, so return it.
            string rawData;

            using (var reader = new StreamReader(filename))
            {
                rawData = reader.ReadToEnd();
            }

            return(rawData);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Caches a response to a search query.
        /// </summary>
        /// <param name="query">The query.</param>
        /// <param name="response">The response.</param>
        /// <exception cref="System.IO.IOException">Thrown if the cache file cannot be written or if the disk is full</exception>
        /// <exception cref="System.ArgumentNullException">Thrown if either paramter is null</exception>
        public void CacheResponse(ISearchQuery query, ICacheableResponse response)
        {
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }

            // Get a unique filename
            var filename = BuildCacheFilename(query);

            try
            {
                // Write the file
                using (var writer = new StreamWriter(filename, false))
                {
                    writer.WriteLine(response.RawData());
                }
            }
            catch (ArgumentException)
            {
                // This search string isn't a valid filename.
                // Just do nothing - don't cache this one.
            }
            catch (PathTooLongException)
            {
                // This search string is reaaalllly long, so it isn't a valid filename.
                // Just do nothing - don't cache this one.
            }
        }
Ejemplo n.º 11
0
        public IDictionary <int, Domain.State> GetStatesOfCountry(int CountryID)
        {
            ISearchQuery query = SearchQueryBuilder.CreateQuery()
                                 .Where("CountryID").Equals(CountryID);

            return(_CommonDA.Search <State>(query).Items.ToDictionary(p => p.ID));
        }
Ejemplo n.º 12
0
 public void EmptyNullInput(string input)
 {
     _searchQuery = new SearchQuery(input);
     Assert.AreEqual(0, _searchQuery.WantedAtoms.Count);
     Assert.AreEqual(0, _searchQuery.UnwantedAtoms.Count);
     //Assert.AreEqual(input, _searchQuery.OriginalInput);
 }
Ejemplo n.º 13
0
        public static IEnumerable <IDocument> GetNewsDocs(string[] providers, Guid searchIndexGuid, out int hitCount, Guid[] categories = null, string terms = null, int skip = 0, int take = 0, string[] orderToSortResults = null)
        {
            ISearchService searchService = ServiceBus.ResolveService <ISearchService>();
            ISearchQuery   searchQuery   = ObjectFactory.Resolve <ISearchQuery>();
            var            queryBuilder  = ObjectFactory.Resolve <IQueryBuilder>();

            //Note: Make sure the Index item has been re-generated via sitfinity's backend to get proper results
            //Guid.Parse("6894B15C-7836-6C70-9642-FF00005F0421")
            var publishingPoint = PublishingManager.GetManager("SearchPublishingProvider")
                                  .GetPublishingPoint(searchIndexGuid) as PublishingPoint;
            string catalogName = (publishingPoint.PipeSettings.First(p => p.PipeName == "SearchIndex") as SearchIndexPipeSettings).CatalogName;

            var orderBy = orderToSortResults != null ? orderToSortResults : new string[] { "PublicationDate DESC" };


            //searchQuery.IndexName = AppSettingsUtility.GetValue<string>("NewsCatalogName");
            searchQuery.IndexName   = catalogName;
            searchQuery.OrderBy     = orderBy;
            searchQuery.Skip        = skip;
            searchQuery.Take        = take;
            searchQuery.SearchGroup = BuildQuery(categories, providers);

            var resultSet = searchService.Search(searchQuery);

            hitCount = resultSet.HitCount;

            log.InfoFormat("search cate:{0}, limit:{1}, hit:{2}", catalogName, take, hitCount);


            return(resultSet.SetContentLinks());
        }
Ejemplo n.º 14
0
        private void LoadTags(ISearchQuery query)
        {
            var tags = new List <IWeightedWord>();
            var srv  = new TagLoadingService {
                Connection = Connection
            };

            srv.ProgressChanged += (sender, tuple) =>
            {
                if (tuple.Item3 != null)
                {
                    tags.Add(tuple.Item3 as Tag);
                }
            };
            srv.Finished += (sender, isSucceed) =>
            {
                if (!isSucceed)
                {
                    AlertError(srv.Error);
                }
                else
                {
                    Tags = tags;
                }
            };
            srv.Execute(query);
        }
Ejemplo n.º 15
0
        public async Task <ISearchResult> SearchQueryAsync(string indexName, ISearchQuery query, ISearchOptions?options = default)
        {
            options ??= new SearchOptions();

            await EnsureBootstrapped();

            var searchRequest = new SearchRequest
            {
                Index   = indexName,
                Query   = query,
                Options = options,
                Token   = ((SearchOptions)options).Token,
                Timeout = ((SearchOptions)options).TimeOut
            };

            async Task <ISearchResult> Func()
            {
                var client1  = LazySearchClient.Value;
                var request1 = searchRequest;

                return(await client1.QueryAsync(request1, request1.Token).ConfigureAwait(false));
            }

            return(await _retryOrchestrator.RetryAsync(Func, searchRequest).ConfigureAwait(false));
        }
Ejemplo n.º 16
0
        private void StartSearch(ISearchQuery searchQuery, Action beforeSearchStartCallback)
        {
            if (searchQuery == null)
            {
                throw new ArgumentNullException("WindowSearcHost.cs -- searchquery is null");
            }
            if (SearchTask != null)
            {
                throw new InvalidOperationException("WindowSearcHost.cs -- search already in progress");
            }
            ++_searchCookie;
            var search = WindowSearch.CreateSearch(_searchCookie, searchQuery, this);

            SearchTask = search;
            beforeSearchStartCallback?.Invoke();
            if (search == null)
            {
                ReportComplete(null, uint.MaxValue);
            }
            else
            {
                ThreadPool.QueueUserWorkItem(task =>
                {
                    if (!(task is ISearchTask searchTask) || searchTask != SearchTask)
                    {
                        return;
                    }
                    searchTask.Start();
                }, search);
            }
        }
        protected async Task SearchQueryHandler(ISearchQuery searchQuery)
        {
            if (searchQuery == null)
            {
                return;
            }

            Collection           = null;
            IsVisibleData        = false;
            IsPageMessageVisible = false;
            IsProgress           = true;

            var list = await UpdateCollection(searchQuery);

            if (list != null)
            {
                Collection = new ObservableCollection <T>(list);
            }

            IsVisibleData        = Collection != null && Collection.Any();
            IsPageMessageVisible = !IsVisibleData;
            IsProgress           = false;

            MessengerInstance.Send(new SearchResultMessage {
                IsFinished = true
            });
        }
Ejemplo n.º 18
0
 public void EmptyQuotesIgnored(string input)
 {
     _searchQuery = new SearchQuery("cat " + input + " horse");
     Assert.AreEqual(0, _searchQuery.UnwantedAtoms.Count);
     Assert.AreEqual(2, _searchQuery.WantedAtoms.Count);
     Assert.AreEqual("cat", _searchQuery.WantedAtoms[0]);
     Assert.AreEqual("horse", _searchQuery.WantedAtoms[1]);
 }
Ejemplo n.º 19
0
        public Dictionary <int, OrderAssignmentStatus> GetSPOrderAssignmentStatuses()
        {
            ISearchQuery query = SearchQueryBuilder.CreateQuery()
                                 .Where("IsServiceProviderInput").Equals(true);
            SearchResult <OrderAssignmentStatus> result = _CommonDA.Search <OrderAssignmentStatus>(query);

            return(result.Items.ToDictionary(p => p.ID));
        }
Ejemplo n.º 20
0
 public void IsolatedMinusIgnored()
 {
     _searchQuery = new SearchQuery("cat - horse");
     Assert.AreEqual(0, _searchQuery.UnwantedAtoms.Count);
     Assert.AreEqual(2, _searchQuery.WantedAtoms.Count);
     Assert.AreEqual("cat", _searchQuery.WantedAtoms[0]);
     Assert.AreEqual("horse", _searchQuery.WantedAtoms[1]);
 }
Ejemplo n.º 21
0
 private void ExecuteQuery(ISearchQuery query)
 {
     if (m_SearchView != null && !string.IsNullOrEmpty(query.searchText))
     {
         ((QuickSearch)m_SearchView).ExecuteSearchQuery(query);
     }
     queryExecuted?.Invoke(query);
 }
Ejemplo n.º 22
0
 public void MixtureOfWantedUnwantedAndQuotes()
 {
     _searchQuery = new SearchQuery("cat -\"dog goat\" -horse \"flea snake\"");
     Assert.AreEqual(2, _searchQuery.UnwantedAtoms.Count);
     Assert.AreEqual(2, _searchQuery.WantedAtoms.Count);
     Assert.AreEqual("cat", _searchQuery.WantedAtoms[0]);
     Assert.AreEqual("flea snake", _searchQuery.WantedAtoms[1]);
     Assert.AreEqual("dog goat", _searchQuery.UnwantedAtoms[0]);
     Assert.AreEqual("horse", _searchQuery.UnwantedAtoms[1]);
 }
        public override ISearchTask CreateSearch(ISearchQuery query)
        {
            string searchTermsParameter = query.Parameters.GetValueOr <string>("searchTerms", null);
            long   startPageParameter   = query.Parameters.GetValueOr <long>("startPage", PaginationParameters.Default.StartPage);
            long   startIndexParameter  = query.Parameters.GetValueOr <long>("startIndex", PaginationParameters.Default.StartIndex);
            int    pageSizeParameter    = query.Parameters.GetValueOr <int>("pageSize", PaginationParameters.Default.PageSize);
            PaginationParameters paginationParameters = new PaginationParameters(startIndexParameter, startPageParameter, pageSizeParameter);

            return((ISearchTask)GetPage(searchTermsParameter, paginationParameters));
        }
        public void SetCurrentQuery(ISearchQuery query)
        {
            var currentItem = FindItemFromQuery(query, rootItem);

            if (currentItem == null)
            {
                return;
            }
            SetSelection(new[] { currentItem.id });
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Stops any currently running search.
        /// </summary>
        public void Stop()
        {
            if (null != m_SearchQuery)
            {
                OnEndSearch(m_SearchQuery);
            }

            m_SearchQuery = null;
            m_Enumerator  = null;
            m_SearchElement.HideProgress();
        }
Ejemplo n.º 26
0
 public void MinusInQuotesTreatedLiterally()
 {
     _searchQuery = new SearchQuery("-cat \"dog -goat\" -horse -\"flea\" -snake");
     Assert.AreEqual(4, _searchQuery.UnwantedAtoms.Count);
     Assert.AreEqual(1, _searchQuery.WantedAtoms.Count);
     Assert.AreEqual("dog -goat", _searchQuery.WantedAtoms[0]);
     Assert.AreEqual("cat", _searchQuery.UnwantedAtoms[0]);
     Assert.AreEqual("horse", _searchQuery.UnwantedAtoms[1]);
     Assert.AreEqual("flea", _searchQuery.UnwantedAtoms[2]);
     Assert.AreEqual("snake", _searchQuery.UnwantedAtoms[3]);
 }
Ejemplo n.º 27
0
        public static IEnumerable <IMatch> AsEnumerable(this ISearchQuery query)
        {
            var match = query.NextMatch();

            while (match != null)
            {
                yield return(match);

                match = query.NextMatch();
            }
        }
Ejemplo n.º 28
0
 /// <summary>
 /// Search domains by Search Query with loading child domains
 /// </summary>
 /// <param name="query"></param>
 /// <param name="nestedPathsToInitialize"></param>
 /// <returns></returns>
 public SearchResult <T> Search(ISearchQuery query, string[] nestedPathsToInitialize)
 {
     using (ConnectionScope.Enter())
     {
         SearchResult <T> result = Search <T>(query);
         if (result.Items.Count == 0 && result.TotalRows > 0)
         {
             result = Search <T>(query.SetPage(result.LastPage));
         }
         return(result);
     }
 }
Ejemplo n.º 29
0
        /// <summary>
        /// Builds a filename unique to a particular search query.
        /// </summary>
        /// <param name="query">The query.</param>
        /// <returns></returns>
        private string BuildCacheFilename(ISearchQuery query)
        {
            // Build a filename which identifies the query. URL encoding should ensure a valid filename.
            var filename = HttpUtility.UrlEncode(query.QueryTerms);

            if (!String.IsNullOrEmpty(query.QueryWithinResultsTerms))
            {
                filename = filename + "#" + HttpUtility.UrlEncode(query.QueryWithinResultsTerms);
            }
            filename = filename + "." + query.Page + "." + query.PageSize + ".cached";
            return(this.folderPath.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar + filename);
        }
Ejemplo n.º 30
0
        public ZipCode GetZipCode(string zipCode)
        {
            ISearchQuery query = SearchQueryBuilder.CreateQuery()
                                 .Where("ZipCodeName").Equals(zipCode);
            SearchResult <ZipCode> zipCodes = _CommonDA.Search <ZipCode>(query);

            if (zipCodes.Items.Count > 0)
            {
                return(zipCodes.Items[0]);
            }
            return(null);
        }
Ejemplo n.º 31
0
        public DocumentFormat GetDocumentFormatByName(string name)
        {
            ISearchQuery query = SearchQueryBuilder.CreateQuery()
                                 .Where("Name").Equals(name);
            SearchResult <DocumentFormat> result = _CommonDA.Search <DocumentFormat>(query);

            if (result.Items.Count > 0)
            {
                return(result.Items.First());
            }
            return(null);
        }
Ejemplo n.º 32
0
        public async Task <ArtifactsList> Execute(ISearchQuery query)
        {
            using (var handler = new HttpClientHandler
            {
                Credentials = new NetworkCredential(_user, _password)
            })
                using (var client = new HttpClient(handler))
                {
                    client.BaseAddress = new Uri(_host);

                    var content = new StringContent(query.Body);

                    try
                    {
                        var response = await client.PostAsync("/artifactory/api/search/aql", content);

                        var responseContent = await response.Content.ReadAsStringAsync();

                        if (response.IsSuccessStatusCode)
                        {
                            try
                            {
                                var result = JsonConvert.DeserializeObject <ArtifactsList>(responseContent);

                                return(result);
                            }
                            catch (Exception e)
                            {
                                throw new ArtifactoryClientException("Can't deserialize response content", e);
                            }
                        }
                        else if (response.StatusCode == HttpStatusCode.BadRequest)
                        {
                            throw new ArtifactoryClientException($"BadRequest: {responseContent}", response.StatusCode);
                        }
                        else if (response.StatusCode == HttpStatusCode.Unauthorized)
                        {
                            throw new ArtifactoryClientException($"Unauthorized: {responseContent}", response.StatusCode);
                        }
                        else
                        {
                            throw new ArtifactoryClientException(responseContent, response.StatusCode);
                        }
                    }
                    catch (Exception e)
                    {
                        throw new ArtifactoryClientException("Enable to process request", e);
                    }
                }
        }
Ejemplo n.º 33
0
        public static IReadOnlyLogbook Build <TModel>(this ISearchQuery <TModel> searchQuery, Conjunction conjunction, out QueryGroup queryGroup) where TModel : class, IModel, new()
        {
            queryGroup = null;

            ILogbook logs = Logger.NewLogbook();

            logs.AddRange(QueryFieldExtension.Build <TModel>(searchQuery.Fields, searchQuery.ValueMap, searchQuery.PredicateMap, searchQuery.OperationMap, out IEnumerable <QueryField> queryFields));

            if (logs.Safely)
            {
                queryGroup = new QueryGroup(queryFields, conjunction);
            }

            return(logs);
        }
Ejemplo n.º 34
0
        public bool Add(ISearchQuery query, QueryType type, Texture2D icon)
        {
            if (string.IsNullOrEmpty(query.searchText))
            {
                return(false);
            }

            QueryBuilder builder = null;

            if (blockMode)
            {
                builder = new QueryBuilder(query.searchText)
                {
                    drawBackground = false,
                    @readonly      = true
                };
                foreach (var b in builder.blocks)
                {
                    b.disableHovering = true;
                }
            }

            if (builder == null || (builder.errors.Count == 0 && builder.blocks.Count > 0))
            {
                var desc = "";
                if (!string.IsNullOrEmpty(query.details))
                {
                    desc = query.details;
                }
                else if (!string.IsNullOrEmpty(query.displayName))
                {
                    desc = query.displayName;
                }

                queries.Add(new QueryData()
                {
                    query       = query, builder = builder,
                    icon        = new GUIContent("", icon),
                    description = new GUIContent(desc, string.IsNullOrEmpty(query.filePath) ? null : QueryHelperWidget.Constants.templateIcon),
                    searchText  = query.searchText,
                    type        = type,
                    tooltip     = new GUIContent("", query.searchText)
                });
                return(true);
            }

            return(false);
        }
Ejemplo n.º 35
0
        public async Task <IActionResult> Search(ISearchFunction searchFunction, HttpRequest request)
        {
            ISearchQuery query      = OpenSearchHelpers.CreateSearchQuery(request.Query, searchFunction);
            ISearchTask  searchTask = searchFunction.CreateSearch(query);

            if (searchTask is IResultSearchTask)
            {
                return(new ObjectResult(await((IResultSearchTask)searchTask).SearchResult()));
            }
            else
            {
                await searchTask.Search();

                return(new OkResult());
            }
        }
Ejemplo n.º 36
0
        private bool IsFilteredQuery(ISearchQuery query, SearchProvider provider)
        {
            if (provider == null)
            {
                return(false);
            }

            if (query.searchText.StartsWith(provider.filterId))
            {
                return(true);
            }

            var queryProviders = query.GetProviderIds().ToArray();

            return(queryProviders.Length == 1 && queryProviders[0] == provider.id);
        }
Ejemplo n.º 37
0
        public override void SetUp()
        {
            _commandFactory = CreateMock<ICommandFactory>();
            _searchQueryFactory = CreateMock<ISearchQueryFactory>();

            _textDiscriminator = new TextDiscriminator(_commandFactory, _searchQueryFactory);
            _searchQuery = Stub<ISearchQuery>();
        }
Ejemplo n.º 38
0
 public ICommand NewFileCommand(CommandType type, ISearchQuery searchQuery)
 {
     return new FileCommand(type, searchQuery);
 }
 public QueryExpression(ISearchQuery query, string propertyName)
 {
     _query = query;
       _propertyName = propertyName;
 }
Ejemplo n.º 40
0
 public IEnumerable<PostalAddressSearchResult> Read(ISearchQuery searchQuery, out int hits)
 {
     return Read(searchQuery, 25, out hits);
 }
Ejemplo n.º 41
0
        public IEnumerable<PostalAddressSearchResult> Read(ISearchQuery searchQuery, int top, out int hits)
        {
            var result = new List<PostalAddressSearchResult>();
            hits = 0;
            var postalAddressFormatter = new PostalAddressFormatter();

            using (var indexreader = IndexReader.Open(Directory, true))
            using (var indexsearch = new IndexSearcher(indexreader))
            {
                var query = new BooleanQuery();
                var terms = searchQuery.SearchTerms;

                AddAllTerms(query, terms);

                Trace.TraceInformation("Query: {0}", query);
                var topDocs = indexsearch.Search(query, top);
                hits = Math.Min(MaxResults, topDocs.TotalHits);
                for (var i = 0; i < topDocs.ScoreDocs.Length; i++)
                {
                    int docId = topDocs.ScoreDocs[i].Doc;
                    var doc = indexsearch.Doc(docId);

                    var docScore = topDocs.ScoreDocs[i];
                    var score = docScore.Score;

                    var item = new PostalAddressSearchResult(score)
                    {
                        Id = doc.Get(address.PropertyName(x => x.Id)),
                        AddressType = doc.Get(address.PropertyName(x => x.AddressType)),
                        BoxBagLobbyName = doc.Get(address.PropertyName(x => x.BoxBagLobbyName)),
                        BoxBagNumber = doc.Get(address.PropertyName(x => x.BoxBagNumber)),
                        BuildingName = doc.Get(address.PropertyName(x => x.BuildingName)),
                        DeliveryServiceType = doc.Get(address.PropertyName(x => x.DeliveryServiceType)),
                        Floor = doc.Get(address.PropertyName(x => x.Floor)),
                        PostCode = doc.Get(address.PropertyName(x => x.PostCode)),
                        RDNumber = doc.Get(address.PropertyName(x => x.RDNumber)),
                        StreetAlpha = doc.Get(address.PropertyName(x => x.StreetAlpha)),
                        StreetDirection = doc.Get(address.PropertyName(x => x.StreetDirection)),
                        StreetName = doc.Get(address.PropertyName(x => x.StreetName)),
                        StreetNumber = doc.Get(address.PropertyName(x => x.StreetNumber)),
                        StreetType = doc.Get(address.PropertyName(x => x.StreetType)),
                        SuburbName = doc.Get(address.PropertyName(x => x.SuburbName)),
                        TownCityMailTown = doc.Get(address.PropertyName(x => x.TownCityMailTown)),
                        UnitId = doc.Get(address.PropertyName(x => x.UnitId)),
                        UnitType = doc.Get(address.PropertyName(x => x.UnitType))
                    };

                    item.Format = postalAddressFormatter.Format(item);

                    if (GetExplanations)
                    {
                        //item.Explanations = indexsearch.Explain(query, docId).GetDetails();
                    }
                    result.Add(item);
                }
            }
            return result.Where(searchResult => !string.IsNullOrWhiteSpace(searchResult.Format.AddressOneLine));
        }
Ejemplo n.º 42
0
 public FileCommand(CommandType type, ISearchQuery searchQuery)
     : base(type)
 {
     _search = searchQuery;
 }
Ejemplo n.º 43
0
 public override void SetUp()
 {
     _fileSystem = CreateMock<IFileSystemFacade>();
     _configSettings = DynamicMock<IConfigSettingsFacade>();
     _searchQuery = CreateMock<ISearchQuery>();
     _fileFinder = new FileFinder(_fileSystem, _configSettings);
 }
Ejemplo n.º 44
0
 public void MultipleWantedWithQuotes()
 {
     _searchQuery = new SearchQuery("cat \"dog goat\" horse \"flea\" snake");
     Assert.AreEqual(5, _searchQuery.WantedAtoms.Count);
     Assert.AreEqual("cat", _searchQuery.WantedAtoms[0]);
     Assert.AreEqual("dog goat", _searchQuery.WantedAtoms[1]);
     Assert.AreEqual("horse", _searchQuery.WantedAtoms[2]);
     Assert.AreEqual("flea", _searchQuery.WantedAtoms[3]);
     Assert.AreEqual("snake", _searchQuery.WantedAtoms[4]);
     Assert.AreEqual(0, _searchQuery.UnwantedAtoms.Count);
 }
Ejemplo n.º 45
0
 private void DisplayTracks(ISearchQuery sq)
 {
     IList<string> result = fileFinder.FindFiles(sq, new List<FileTypes>(SEARCHFOR), FileListSort.None);
     if ((null == result) || (result.Count == 0))
         console.WriteLine("No files found");
     else
         foreach (string file in result)
             console.WriteLine(file);
 }
Ejemplo n.º 46
0
 public void OneWantedWithQuotes()
 {
     _searchQuery = new SearchQuery("\"cat\"");
     Assert.AreEqual(1, _searchQuery.WantedAtoms.Count);
     Assert.AreEqual("cat", _searchQuery.WantedAtoms[0]);
     Assert.AreEqual(0, _searchQuery.UnwantedAtoms.Count);
 }
Ejemplo n.º 47
0
 public void SpaceAfterOpenQuoteTreatedLiterally()
 {
     _searchQuery = new SearchQuery("\" dog goat\"");
     Assert.AreEqual(0, _searchQuery.UnwantedAtoms.Count);
     Assert.AreEqual(1, _searchQuery.WantedAtoms.Count);
     Assert.AreEqual(" dog goat", _searchQuery.WantedAtoms[0]);
 }
Ejemplo n.º 48
0
 public void TwoMinusesTreatedAsUnwantedWithMinus()
 {
     _searchQuery = new SearchQuery("cat --dog horse");
     Assert.AreEqual(1, _searchQuery.UnwantedAtoms.Count);
     Assert.AreEqual(2, _searchQuery.WantedAtoms.Count);
     Assert.AreEqual("-dog", _searchQuery.UnwantedAtoms[0]);
     Assert.AreEqual("cat", _searchQuery.WantedAtoms[0]);
     Assert.AreEqual("horse", _searchQuery.WantedAtoms[1]);
 }
Ejemplo n.º 49
0
 public IList<string> FindFiles(ISearchQuery searchQuery, IList<FileTypes> fileTypes)
 {
     return FindFiles(searchQuery, fileTypes, FileListSort.None);
 }
Ejemplo n.º 50
0
 public IList<string> FindFiles(ISearchQuery searchQuery, FileTypes fileType, FileListSort fileListSort)
 {
     return FindFiles(searchQuery, new List<FileTypes>(new FileTypes[] { fileType }), fileListSort);
 }
        public IResultSet Search(ISearchQuery query)
        {
            AmazonCloudSearchDomainConfig config = new AmazonCloudSearchDomainConfig();
            config.ServiceURL = "http://search-index2-cdduimbipgk3rpnfgny6posyzy.eu-west-1.cloudsearch.amazonaws.com/";
            AmazonCloudSearchDomainClient domainClient = new AmazonCloudSearchDomainClient("AKIAJ6MPIX37TLIXW7HQ", "DnrFrw9ZEr7g4Svh0rh6z+s3PxMaypl607eEUehQ", config);
            SearchRequest searchRequest = new SearchRequest();
            List<string> suggestions = new List<string>();
            StringBuilder highlights = new StringBuilder();
            highlights.Append("{\'");

            if (query == null)
                throw new ArgumentNullException("query");

            foreach (var field in query.HighlightedFields)
            {
                if (highlights.Length > 2)
                {
                    highlights.Append(", \'");
                }

                highlights.Append(field.ToUpperInvariant());
                highlights.Append("\':{} ");
                SuggestRequest suggestRequest = new SuggestRequest();
                Suggester suggester = new Suggester();
                suggester.SuggesterName = field.ToUpperInvariant() + "_suggester";
                suggestRequest.Suggester = suggester.SuggesterName;
                suggestRequest.Size = query.Take;
                suggestRequest.Query = query.Text;
                SuggestResponse suggestion = domainClient.Suggest(suggestRequest);
                foreach (var suggest in suggestion.Suggest.Suggestions)
                {
                    suggestions.Add(suggest.Suggestion);
                }
            }

            highlights.Append("}");

            if (query.Filter != null)
            {
                searchRequest.FilterQuery = this.BuildQueryFilter(query.Filter);
            }

            if (query.OrderBy != null)
            {
                searchRequest.Sort = string.Join(",", query.OrderBy);
            }

            if (query.Take > 0)
            {
                searchRequest.Size = query.Take;
            }

            if (query.Skip > 0)
            {
                searchRequest.Start = query.Skip;
            }

            searchRequest.Highlight = highlights.ToString();
            searchRequest.Query = query.Text;
            searchRequest.QueryParser = QueryParser.Simple;
            var result = domainClient.Search(searchRequest).SearchResult;

            return new AmazonResultSet(result, suggestions);
        }
Ejemplo n.º 52
0
        public IList<string> FindFiles(ISearchQuery searchQuery, IList<FileTypes> fileTypes, FileListSort fileListSort)
        {
            List<string> result = new List<string>();

            if (configSettings.MusicDirectories.Count == 0)
                return result;
            StringBuilder search = new StringBuilder();

            foreach (string wa in searchQuery.WantedAtoms) {
                search.Append("*");
                search.Append(wa);
            }
            search.Append("*.");

            foreach (FileTypes fileTypeEnum in fileTypes) {
                string fileType;
                if (FileTypes.ALL == fileTypeEnum)
                    fileType = "*";
                else
                    fileType = fileTypeEnum.ToString();

                fileType = fileType.ToLower();

                foreach (string musicDir in configSettings.MusicDirectories) {
                    string[] found;
                    try {
                        //PROBLEM! http://www.mono-project.com/IOMap also man mono
                        found = fileSystem.GetFiles(musicDir, search + fileType, SearchOption.AllDirectories);
                    }
                    catch {
                        found = new string[0];
                    }
                    foreach (string hit in found) {
                        //don't add it twice, and discard any extension-greater-than-three-characters microsoft retardedness:
                        //http://msdn2.microsoft.com/en-us/library/ms143316(VS.80).aspx
                        if ((result.Contains(hit)) ||
                            ((Path.GetExtension(hit).ToLower() != ("." + fileType).ToLower()) && (FileTypes.ALL != fileTypeEnum)))
                        continue;

                        //also don't add it if it contains unwanted atoms
                        bool add = true;
                        foreach (string uwa in searchQuery.UnwantedAtoms)
                            if (Regex.IsMatch(Path.GetFileNameWithoutExtension(hit), Regex.Escape(uwa), RegexOptions.IgnoreCase)) {
                                add = false;
                                break;
                            }
                        if (add)
                            result.Add(hit);
                    }
                }
            }
            switch (fileListSort) {
                case FileListSort.SmallestFirst:
                    result.Sort(new FilenameComparer(true));
                    break;
                case FileListSort.LargestFirst:
                    result.Sort(new FilenameComparer(false));
                    break;
                case FileListSort.Random:
                    Randomise(result);
                    break;
            }

            return result;
        }
Ejemplo n.º 53
0
 public void UnclosedQuoteReachingEndOfLineTreatedAsClosed()
 {
     _searchQuery = new SearchQuery("cat \"dog horse");
     Assert.AreEqual(0, _searchQuery.UnwantedAtoms.Count);
     Assert.AreEqual(2, _searchQuery.WantedAtoms.Count);
     Assert.AreEqual("cat", _searchQuery.WantedAtoms[0]);
     Assert.AreEqual("dog horse", _searchQuery.WantedAtoms[1]);
 }
Ejemplo n.º 54
0
 public void MultipleUnwantedNoQuotes()
 {
     _searchQuery = new SearchQuery("-cat -dog -goat");
     Assert.AreEqual(3, _searchQuery.UnwantedAtoms.Count);
     Assert.AreEqual("cat", _searchQuery.UnwantedAtoms[0]);
     Assert.AreEqual("dog", _searchQuery.UnwantedAtoms[1]);
     Assert.AreEqual("goat", _searchQuery.UnwantedAtoms[2]);
     Assert.AreEqual(0, _searchQuery.WantedAtoms.Count);
 }