Ejemplo n.º 1
0
        public void CanSearchForTag()
        {
            // ACT
            var result = _command.Execute(new[]
            {
                "/q:amenity=bar",
            }).Wait();

            // ASSERT
            Assert.IsNotNullOrEmpty(result);
            Assert.IsTrue(result.Contains("Node"));
            Assert.IsTrue(result.Contains("Way"));
            Assert.IsTrue(result.Contains("Relation"));
        }
Ejemplo n.º 2
0
        /// <summary>
        ///     Adds the action.
        /// </summary>
        public virtual void AddAction()
        {
            var w = AppEx.Container.GetInstance <IViewModel>(AddViewModeKey);

            if (!BeforeAdd((T)w.Model))
            {
                return;
            }
            if (w.View.ShowDialog() == true)
            {
                IBaseDataService <T> service   = GetDataService();
                ResultMsg            resultMsg = service.Add((T)w.Model);
                if (resultMsg.IsSuccess)
                {
                    _Collection.Clear();
                    if (SearchCommand.CanExecute(null))
                    {
                        SearchCommand.Execute(null);
                    }
                }
                else
                {
                    MessageBox.Show("添加失败", "失败", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
Ejemplo n.º 3
0
        public void SearchCommand_ExecuteRequest_2()
        {
            int returnCode = 0;
            Mock <IIrbisConnection> mock       = GetConnectionMock();
            IIrbisConnection        connection = mock.Object;
            SearchCommand           command    = new SearchCommand(connection)
            {
                Database                = "IBIS",
                SearchExpression        = "A=AUTHOR$",
                MinMfn                  = 0,
                MaxMfn                  = 0,
                SequentialSpecification = "p(v300)",
                FormatSpecification     = "(v300/)"
            };
            ResponseBuilder builder = new ResponseBuilder()
                                      .StandardHeader(CommandCode.Search, 123, 456)
                                      .NewLine()
                                      .Append(returnCode)
                                      .NewLine()
                                      .Append(0)
                                      .NewLine();
            TestingSocket socket = (TestingSocket)connection.Socket;

            socket.Response = builder.Encode();
            ClientQuery    query    = command.CreateQuery();
            ServerResponse response = command.Execute(query);

            Assert.AreEqual(returnCode, response.ReturnCode);
            Assert.IsNotNull(command.Found);
            Assert.AreEqual(0, command.Found.Count);
        }
Ejemplo n.º 4
0
        private void StartSearch(IContentSearchItemVM item)
        {
            if (DelayCTS != null && !DelayCTS.IsCancellationRequested)
            {
                DelayCTS.Cancel();
                DelayCTS = new CancellationTokenSource();
            }

            if (HintsCTS != null && !HintsCTS.IsCancellationRequested)
            {
                HintsCTS.Cancel();
            }

            SetProperty(ref _searchText, item.SearchText, "SearchText");

            ContentVm.SearchText = SearchText;

            SearchCommand.Execute(null);

            InvokeOnMainThread(() =>
            {
                HistoryVisible = false;
                HintsVisible   = false;

                RaisePropertyChanged(() => ContentVisible);
            });
        }
		public virtual void SimpleSearch()
		{
			var command = new SearchCommand(_connection, new SearchQuery("devil"));
			command.Execute();
			Assert.AreEqual(1, command.Result.QueryResults.Count);
            Assert.AreEqual(4, command.Result.QueryResults[0].Count);
        }
Ejemplo n.º 6
0
 private void Button_Click(object sender, RoutedEventArgs e)
 {
     if (SearchCommand != null)
     {
         SearchCommand.Execute(tb.Text);
     }
 }
Ejemplo n.º 7
0
        public ExchangesViewModel()
        {
            Exchanges = DbContext.Exchanges.ToList();


            FilteredExchanges = new ReactiveList <Exchange>(Exchanges.OrderBy(x => x.Name));
            SelectedExchange  = Exchanges.First();
            var canExecute = this.WhenAny(x => x.SelectedExchange, x => x.Value != null);

            AddCommand    = ReactiveCommand.Create(Add);
            DeleteCommand = ReactiveCommand.Create(Delete, canExecute);
            EditCommand   = ReactiveCommand.Create(Modify, canExecute);
            var canSearch = this.WhenAny(x => x.SearchBoxText,
                                         x => !string.IsNullOrWhiteSpace(x.Value));

            this.WhenAnyObservable(x => x.FilteredExchanges.ItemsAdded)
            .Subscribe(async item => { await ItemsAddedTask(item); });

            this.WhenAnyObservable(x => x.FilteredExchanges.ItemsRemoved)
            .Subscribe(async item => { await ItemsRemovedTask(item); });


            DeleteCommand = ReactiveCommand.Create(() => { FilteredExchanges.Remove(SelectedExchange); });

            SearchCommand = ReactiveCommand.Create(Search, canSearch);

            this.WhenAny(x => x.SearchBoxText, x => x.Value)
            .Subscribe(text => { SearchCommand.Execute(); });
        }
Ejemplo n.º 8
0
        public AutoCompleteView()
        {
            //InitializeComponent();
            stkBase = new StackLayout();
            var innerLayout = new StackLayout();

            entText = new Entry()
            {
                HorizontalOptions = LayoutOptions.FillAndExpand,
                VerticalOptions   = LayoutOptions.Start
            };
            btnSearch = new Button()
            {
                VerticalOptions = LayoutOptions.Center,
                Text            = "Search"
            };

            lstSugestions = new ListView()
            {
                HeightRequest = 250,
                HasUnevenRows = true
            };

            innerLayout.Children.Add(entText);
            innerLayout.Children.Add(btnSearch);
            stkBase.Children.Add(innerLayout);
            stkBase.Children.Add(lstSugestions);

            Content = stkBase;


            entText.TextChanged += (s, e) =>
            {
                Text = e.NewTextValue;
            };
            btnSearch.Clicked += (s, e) =>
            {
                if (SearchCommand != null && SearchCommand.CanExecute(Text))
                {
                    SearchCommand.Execute(Text);
                }
            };
            lstSugestions.ItemSelected += (s, e) =>
            {
                entText.Text = GetSearchString(e.SelectedItem);

                AvailableSugestions.Clear();
                ShowHideListbox(false);
                SelectedCommand.Execute(e);
                if (ExecuteOnSugestionClick &&
                    SearchCommand != null && SearchCommand.CanExecute(Text))
                {
                    SearchCommand.Execute(e);
                }
            };
            AvailableSugestions = new ObservableCollection <object>();
            this.ShowHideListbox(false);
            lstSugestions.ItemsSource = this.AvailableSugestions;
            //lstSugestions.ItemTemplate = this.SugestionItemDataTemplate;
        }
        public AutoCompleteView()
        {
            InitializeComponent();
            entText.TextChanged += (s, e) =>
            {
                Text = e.NewTextValue;
            };
            btnSearch.Clicked += (s, e) =>
            {
                if (SearchCommand != null && SearchCommand.CanExecute(Text))
                {
                    SearchCommand.Execute(Text);
                }
            };
            lstSugestions.ItemSelected += (s, e) =>
            {
                entText.Text = GetSearchString(e.SelectedItem);

                AvailableSugestions.Clear();
                ShowHideListbox(false);
                SelectedCommand.Execute(e);
                if (ExecuteOnSugestionClick &&
                    SearchCommand != null && SearchCommand.CanExecute(Text))
                {
                    SearchCommand.Execute(e);
                }
            };
            AvailableSugestions = new ObservableCollection <object>();
            this.ShowHideListbox(false);
            lstSugestions.ItemsSource = this.AvailableSugestions;
            //lstSugestions.ItemTemplate = this.SugestionItemDataTemplate;
        }
Ejemplo n.º 10
0
 private void MemberCodeKeyDown(object sender, KeyEventArgs e)
 {
     if (e.Key == Key.Enter || e.Key == Key.Return)
     {
         SearchCommand.Execute(null);
     }
 }
Ejemplo n.º 11
0
        public SearchViewModel()
        {
            ContentId = ToolContentId;

            loader = new JsonOptionsLoader();

            QueryEditor = new QueryEditorViewModel(Session, () =>
            {
                if (SearchCommand.CanExecute(null))
                {
                    SearchCommand.Execute(null);
                }
            });
            QueryEditor.SendToSearchCommand.IsVisible = false;

            var ests = EntityQuery <Estimator> .All(Session)();

            Estimators        = new ObservableCollection <Estimator>(ests);
            SelectedEstimator = ests.FirstOrDefault();

            emh.Add(
                this.Subscribe(Event.SendToSearch, (e) =>
            {
                object pack = null;
                try
                {
                    pack = e.GetValue <object>(MessageKeys.ToSearchPackage);
                }
                catch
                {
                    return;
                }

                OpenHrSearch();

                var hrs  = pack as IEnumerable <HealthRecord>;
                var hios = pack as IEnumerable <ConfWithHio>;
                var opt  = pack as SearchOptions;

                if (hrs != null && hrs.Any())
                {
                    RecieveHealthRecords(hrs);
                }
                else if (hios != null && hios.Any())
                {
                    RecieveHrItemObjects(hios);
                }
                else if (opt != null)
                {
                    RecieveOptions(opt);
                }

                Contract.Assume(LastRecieverQueryBlock != null);
                Activate();
            })

                );

            ControlsVisible = true;
        }
Ejemplo n.º 12
0
 private void InitView()
 {
     lvMain.Dispatcher.Invoke(
         new Action(
             delegate
     {
         try
         {
             lvMain.ItemsSource = DisplayList;
             SearchCommand.Execute(null);
         }
         catch (Exception ex)
         {
             Framework.MessageBox mb = new Framework.MessageBox();
             mb.Topmost = true;
             mb.Title   = "异常提示";
             mb.Message = ex.Message;
             mb.ShowDialog();
         }
     }
             ));
     lbPageInfo.Dispatcher.Invoke(
         new Action(
             delegate
     {
         lbPageInfo.Content = string.Format("当前第{0}页,共{1}页", _currentPage, _totalPage);
     }
             ));
 }
Ejemplo n.º 13
0
 void PaymentNoKeyDown(object sender, KeyEventArgs e)
 {
     if (e.Key == Key.Enter || e.Key == Key.Return)
     {
         SearchCommand.Execute(null);
     }
 }
Ejemplo n.º 14
0
        private void OnBack()
        {
            _history.Pop();
            Id = _history.Pop();

            SearchCommand.Execute(null);
        }
Ejemplo n.º 15
0
        /// <summary>
        ///     Edits the action.
        /// </summary>
        /// <param name="model">The model.</param>
        public void EditAction(T model)
        {
            if (model == null)
            {
                MessageBox.Show("请选择要编辑的记录", "失败", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            var w = AppEx.Container.GetInstance <IViewModel>(EditViewModeKey);

            w.Model = model;
            BeforeEdit(w, model);
            if (w.View.ShowDialog() == true)
            {
                IBaseDataService <T> service   = GetDataService();
                ResultMsg            resultMsg = service.Edit((T)w.Model);
                if (resultMsg.IsSuccess)
                {
                    _Collection.Clear();
                    if (SearchCommand.CanExecute(null))
                    {
                        SearchCommand.Execute(null);
                    }
                }
                else
                {
                    MessageBox.Show("修改失败", "失败", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
Ejemplo n.º 16
0
        public virtual void SimpleSearch()
        {
            var command = new SearchCommand(_connection, new SearchQuery("devil"));

            command.Execute();
            Assert.AreEqual(1, command.Result.QueryResults.Count);
            Assert.AreEqual(4, command.Result.QueryResults[0].Count);
        }
        private void Button_Clicked(object sender, EventArgs e)
        {
            var sortColumn = _selectedSortColumn.CloneJson();

            sortColumn.Ascending = _isAscending;
            _filter.SortColumn   = sortColumn;
            SearchCommand?.Execute(_filter);
        }
Ejemplo n.º 18
0
 private void FocusSearchFieldAction()
 {
     if (!IsActive)
     {
         return;
     }
     SearchCommand.Execute(null);
 }
Ejemplo n.º 19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AutoCompleteView"/> class.
        /// </summary>
        public AutoCompleteView()
        {
            _availableSuggestions = new ObservableCollection <object>();
            _stkBase = new StackLayout();
            var innerLayout = new StackLayout();

            _entText = new Entry {
                HorizontalOptions = TextHorizontalOptions,
                VerticalOptions   = TextVerticalOptions,
                TextColor         = TextColor,
                BackgroundColor   = TextBackgroundColor
            };
            _btnSearch = new Button {
                VerticalOptions   = SearchVerticalOptions,
                HorizontalOptions = SearchHorizontalOptions,
                Text = SearchText
            };

            _lstSuggestions = new ListView {
                HeightRequest = SuggestionsHeightRequest,
                HasUnevenRows = true
            };

            innerLayout.Children.Add(_entText);
            innerLayout.Children.Add(_btnSearch);
            _stkBase.Children.Add(innerLayout);
            _stkBase.Children.Add(_lstSuggestions);

            Content = _stkBase;


            _entText.TextChanged += (s, e) => {
                Text = e.NewTextValue;
                OnTextChanged(e);
            };
            _btnSearch.Clicked += (s, e) => {
                if (SearchCommand != null && SearchCommand.CanExecute(Text))
                {
                    SearchCommand.Execute(Text);
                }
            };
            _lstSuggestions.ItemSelected += (s, e) => {
                _entText.Text = e.SelectedItem.ToString();

                _availableSuggestions.Clear();
                ShowHideListbox(false);
                OnSelectedItemChanged(e.SelectedItem);

                if (ExecuteOnSuggestionClick &&
                    SearchCommand != null &&
                    SearchCommand.CanExecute(Text))
                {
                    SearchCommand.Execute(e);
                }
            };
            ShowHideListbox(false);
            _lstSuggestions.ItemsSource = _availableSuggestions;
        }
Ejemplo n.º 20
0
        private void OnSearch()
        {
            RaiseEvent(new RoutedEventArgs(SearchEvent));

            if (SearchCommand.CanExecute(null))
            {
                SearchCommand.Execute(null);
            }
        }
        private void OnSearch(object sender, EventArgs e)
        {
            ResignFirstResponder();

            if (SearchCommand != null)
            {
                SearchCommand.Execute(SearchBar.Text);
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Invokes the SearchTextChanged event handler and executes the SearchCommand
        /// </summary>
        public void OnSearchTextChanged(object sender, EventArgs e)
        {
            if (SearchTextChanged != null)
            {
                SearchTextChanged(this, e);
            }

            SearchCommand?.Execute(null);
        }
Ejemplo n.º 23
0
        public override void OnNavigatedTo(INavigationParameters parameters)
        {
            base.OnNavigatedTo(parameters);

            if (parameters.TryGetValue("query", out string query))
            {
                SearchQuery = query;
                SearchCommand?.Execute(null);
            }
        }
Ejemplo n.º 24
0
 private void mainpanel_KeyDown(object sender, KeyEventArgs e)
 {
     if (e.Key == Key.Enter)
     {
         if (SearchCommand != null)
         {
             SearchCommand.Execute(SearchPhraseList);
         }
     }
 }
Ejemplo n.º 25
0
        private void Search(string inputText)
        {
            if (SearchCommand == null)
            {
                return;
            }

            ActivityIndicatorOn();
            SearchCommand.Execute(inputText);
        }
Ejemplo n.º 26
0
 private void Button_Clicked(object sender, EventArgs e)
 {
     SearchCommand?.Execute(new NotificationFilter
     {
         StartDate  = _startDate,
         EndDate    = _endDate,
         SortColumn = (NotificationSortColumns)_selectedSortColumn.Key,
         Ascending  = _ascending
     });
 }
Ejemplo n.º 27
0
        private async void Button_Clicked(object sender, EventArgs e)
        {
            if (!await _filterModel.Validate())
            {
                return;
            }
            var filter = _filterModel.ToFilter();

            SearchCommand?.Execute(filter);
        }
Ejemplo n.º 28
0
        private void CompleteBoxOnTextChanged(object sender, TextChangedEventArgs textChangedEventArgs)
        {
            if (SearchCommand != null && !string.IsNullOrEmpty(_completeBox.Text))
            {
                SearchCommand.Execute(_completeBox.Text);
            }

            if (string.IsNullOrEmpty(_completeBox.Text))
            {
            }
        }
Ejemplo n.º 29
0
        private static void SearchExecute(SearchOptions options)
        {
            Console.WriteLine("Started to Search, please wait...");
            var command = new SearchCommand(options);

            command.Execute();
            Console.WriteLine("Summary");
            Console.WriteLine($" Number of files searched were {command.Stats.TotalFiles}.");
            Console.WriteLine($" Number of instances of text/strings found were {command.Stats.TotalInstances}.");
            Console.WriteLine($" Number files found that contained text/strings were {command.Stats.FoundFiles}.");
        }
Ejemplo n.º 30
0
        private void ListBoxDoubleClickCommand_Executing(object sender, ExecutingEventArgs e)
        {
            var record = e.Parameter as ResultModel;

            if (record == null)
            {
                return;
            }
            ResultCollection.SearchContent = record.Content;
            SearchCommand.Execute(null);
        }
Ejemplo n.º 31
0
 private bool ExecuteCommand(string text)
 {
     if (!string.IsNullOrEmpty(text) && SearchCommand != null)
     {
         if (SearchCommand.CanExecute(text))
         {
             SearchCommand.Execute(text);
             return(true);
         }
     }
     return(false);
 }
        public IEnumerable<int> Execute(BookSearchCriterion criterion)
        {
            using (var connection = new TcpConnection("localhost", 9317))
            {
                var command = new SearchCommand(connection);

                connection.Open();
                command.Execute();

                IEnumerable<int> result = null;

                return result;
            }
        }
Ejemplo n.º 33
0
 /// <summary>
 /// 建立連接并獲取符合條件的idList
 /// GetIdList獲取查詢框對應的idList
 /// GetFlagList獲取食安關鍵字對應的idList
 /// GetSphinxExcludeIdList獲取要排除的idList
 /// </summary>
 /// <param name="query"></param>
 public List<int> GetIdList(string key,int MaxMatches)
 {
     List<int> idList = new List<int>();
     using (TcpConnection connection = new PersistentTcpConnection(_sphinxHost, _sphinxPort))
     {
        
         try
         {
             ///獲得全部要搜索的關鍵字
             SearchCommand search = new SearchCommand(connection);
             ///綁定搜索關鍵字
             SearchQuery searchQuery = new SearchQuery(key);
             searchQuery.Limit = searchQuery.MaxMatches = MaxMatches;
             search.QueryList.Add(searchQuery);
             search.Execute();
             if (search.Result.Status == CommandStatus.Warning)
             {
                 foreach (var s in search.Result.Warnings)
                 {
                     warnings += s;
                 }
             }
             foreach (SearchQueryResult res in search.Result.QueryResults)
             {
                 if (res.HasWarning)
                     warnings += res.Warning;
                 foreach (Match match in res.Matches)
                 {
                     ///取出全部符合條件的Id
                     int strId = Convert.ToInt32(match.DocumentId);
                     if (!idList.Contains(strId))
                     {
                         idList.Add(strId);
                     }
                 }
             }
                 
         }
         catch (SphinxException ex)
         {
             throw new Exception("ProductSearchDao-->GetIdList:warnings: " + warnings + "連接失敗信息:" + ex.Message);
         }
     }
     return idList;
 }
Ejemplo n.º 34
0
        public IList<SearchQueryResult> searchBible(
            String searchString,
            int translation,
            int bookID,
            int testament)
        {
            using (ConnectionBase connection = new PersistentTcpConnection("127.0.0.1", 9312))
            {
                // Create new search query object and pass query text as argument
                SearchQuery searchQuery = new SearchQuery(searchString);
                // Set match mode to SPH_MATCH_EXTENDED2
                searchQuery.MatchMode = MatchMode.All;
                // Add Sphinx index name to list
                searchQuery.Indexes.Add("test1");
                // Setup attribute
                searchQuery.AttributeFilters.Add("translation", translation, false);
                if (bookID != -1)
                {
                    searchQuery.AttributeFilters.Add("book", bookID, false);
                }

                if (testament != -1)
                {
                    searchQuery.AttributeFilters.Add("testament", testament, false);
                }
                // Set amount of matches will be returned to client
                searchQuery.Limit = 50;

                // Create search command object
                SearchCommand searchCommand = new SearchCommand(connection);
                // Add newly created search query object to query list
                searchCommand.QueryList.Add(searchQuery);
                // Execute command on server and obtain results
                searchCommand.Execute();
                return searchCommand.Result.QueryResults;
            }
        }
Ejemplo n.º 35
0
        private string DoSearch()
        {
            // set hostname and port defaults
            using (TcpConnection connection = new PersistentTcpConnection(Host, Port))
            {

                SearchCommand search = new SearchCommand(connection);
                SearchQuery query = new SearchQuery(QueryString);
                // Sphinx indexes
                query.Indexes.UnionWith(Indexes);
                // select fields clause
                query.Select = SelectFields;
                // match type
                query.MatchMode = MatchMode;
                // ranking
                query.RankingMode = RankingMode;
                // comment
                query.Comment = Comment;
                // sorting
                query.SortMode = SortMode;
                query.SortBy = SortClause;
                // limits
                query.Limit = query.MaxMatches = MaxMatches;
                // document id filtering
                query.MinDocumentId = MinDocumentId;
                query.MaxDocumentId = MaxDocumentId;
                // grouping
                query.GroupFunc = GroupFunc;
                query.GroupBy = GroupBy;
                query.GroupSort = GroupSortBy;
                query.GroupDistinct = GroupDistinct;

                //query.AttributeFilters.Add(new AttributeFilterRangeDateTime("PublishDate", PublicationStartDate.Value, PublicationEndDate.Value, false));

                // index weights
                foreach (NameValuePair item in _indexWeights)
                {
                    if (!query.IndexWeights.ContainsKey(item.Name))
                        query.IndexWeights.Add(item.Name, item.Value);
                }

                // fields weights
                foreach (NameValuePair item in _fieldWeights)
                {
                    if (!query.FieldWeights.ContainsKey(item.Name)) 
                        query.FieldWeights.Add(item.Name, item.Value);
                }

                // attribute overrides
                foreach (AttributeOverrideMapping item in _attributeOverrides)
                {
                    AttributeOverrideBase attr;
                    AttributeType type = (AttributeType) item.Type;
                    if (!query.AttributeOverrides.Contains(item.Name))
                    {
                        switch (type)
                        {
                            case AttributeType.Integer:
                                Dictionary<long, int> ints = new Dictionary<long, int>();
                                ints.Add(item.DocumentId, Convert.ToInt32(item.Value));
                                attr = new AttributeOverrideInt32(item.Name, ints);
                                break;
                            case AttributeType.Bigint:
                                Dictionary<long, long> longs = new Dictionary<long, long>();
                                longs.Add(item.DocumentId, Convert.ToInt64(item.Value));
                                attr = new AttributeOverrideInt64(item.Name, longs);
                                break;
                            case AttributeType.Boolean:
                                Dictionary<long, bool> bools = new Dictionary<long, bool>();
                                bools.Add(item.DocumentId, Convert.ToBoolean(item.Value));
                                attr = new AttributeOverrideBoolean(item.Name, bools);
                                break;
                            case AttributeType.Float:
                                Dictionary<long, float> floats = new Dictionary<long, float>();
                                floats.Add(item.DocumentId, float.Parse(item.Value.ToString()));
                                attr = new AttributeOverrideFloat(item.Name, floats);
                                break;
                            case AttributeType.Ordinal:
                                Dictionary<long, int> ordinals = new Dictionary<long, int>();
                                ordinals.Add(item.DocumentId, Convert.ToInt32(item.Value));
                                attr = new AttributeOverrideOrdinal(item.Name, ordinals);
                                break;
                            case AttributeType.Timestamp:
                                Dictionary<long, DateTime> timestamps = new Dictionary<long, DateTime>();
                                timestamps.Add(item.DocumentId, Convert.ToDateTime(item.Value));
                                attr = new AttributeOverrideDateTime(item.Name, timestamps);
                                break;
                            default:
                                throw new InvalidOperationException("Unknown attribute type");
                        }
                        query.AttributeOverrides.Add(attr);
                    }
                    else
                    {
                        attr = query.AttributeOverrides[item.Name];
                        if (type != attr.AttributeType) throw new InvalidOperationException("Attribute type mismatch");
                        switch (type)
                        {
                            case AttributeType.Integer:
                                ((AttributeOverrideInt32) attr).Values.Add(item.DocumentId, Convert.ToInt32(item.Value));
                                break;
                            case AttributeType.Bigint:
                                ((AttributeOverrideInt64)attr).Values.Add(item.DocumentId, Convert.ToInt64(item.Value));
                                break;
                            case AttributeType.Boolean:
                                ((AttributeOverrideBoolean)attr).Values.Add(item.DocumentId, Convert.ToBoolean(item.Value));
                                break;
                            case AttributeType.Float:
                                ((AttributeOverrideFloat)attr).Values.Add(item.DocumentId, float.Parse(item.Value.ToString()));
                                break;
                            case AttributeType.Ordinal:
                                ((AttributeOverrideOrdinal)attr).Values.Add(item.DocumentId, Convert.ToInt32(item.Value));
                                break;
                            case AttributeType.Timestamp:
                                ((AttributeOverrideDateTime)attr).Values.Add(item.DocumentId, Convert.ToDateTime(item.Value));
                                break;
                            default:
                                throw new InvalidOperationException("Unknown attribute type");
                        }
                    }
                }

                // add new query
                search.QueryList.Add(query);

                // run the query and get the results
                string output = "";
                try
                {
                    search.Execute();
                }
                catch (SphinxException ex)
                {
                    output = "<h2 style='color: red;'>Error is occured:<h2>" + ex.Message;
                    return output;
                }
                if (search.Result.Status == CommandStatus.Warning)
                {
                    output = "<h2 style='color: olive;'>Warnings: </h2><ul>";
                    foreach (var s in search.Result.Warnings)
                    {
                        output += "<li>" + s + "</li>";
                    }
                    output += "</ul>";
                }
                foreach (SearchQueryResult res in search.Result.QueryResults)
                {
                    output += ParseResult(res);
                }
                return output;
            }
        }
Ejemplo n.º 36
0
        private IEnumerable<SphinxDocumentAnnounce> GetSphinxSearchResults(string q, string[] indexes = null)
        {
            if (string.IsNullOrEmpty(q))
                return new SphinxDocumentAnnounce[0];

            using (ConnectionBase connection = new PersistentTcpConnection(MeridianMonitor.Default.SphinxHost, MeridianMonitor.Default.SphinxPort))
            {
                q = q.Replace(" -", "¦").Replace("-", " ").Replace("¦", " -").Replace("!", "\\!").Replace("?", "\\?").Replace("@", "\\@");

                if (q.LastIndexOf('-') == (q.Length - 1))
                {
                    q = q.Substring(0, q.LastIndexOf('-') - 1).Trim();
                }

                q = string.Join(" ", q.Split(' ').Select(s => s.Trim()));
                // Create new search query object and pass query text as argument
                SearchQuery searchQuery = new SearchQuery(q);
                // Set match mode to SPH_MATCH_EXTENDED2
                searchQuery.MatchMode = MatchMode.All;

                string[] protos = indexes ?? new string[]
                    {
                        typeof(hotels).Name,
                        //typeof(countries).Name,
                        typeof(deseases).Name,
                        typeof(cure_profiles).Name,
                        typeof(health_factors).Name,
                        //typeof(regions).Name,
                        //typeof(resort_zones).Name,
                        typeof(resorts).Name,
                        typeof(treatment_options).Name,
                        "static_pages",
                        typeof(dictionary).Name
                    };

                var byIndexResults = new Dictionary<string, List<SphinxDocumentAnnounce>>();
                foreach (var protoIndex in protos)
                {
                    searchQuery.Indexes.Add(protoIndex);
                    byIndexResults[protoIndex] = new List<SphinxDocumentAnnounce>();
                }

                searchQuery.Limit = 5000;
                SearchCommand searchCommand = new SearchCommand(connection);
                searchCommand.QueryList.Add(searchQuery);
                searchCommand.Execute();

                var pubResult = new List<SphinxDocumentAnnounce>();
                foreach (SearchQueryResult result in searchCommand.Result.QueryResults)
                {
                    foreach (var match in result.Matches)
                    {
                        var otype = match.AttributesValues["objecttype"].GetValue().ToString().Trim();
                        var entityId = Convert.ToInt64(match.AttributesValues["entityid"].GetValue());
                        var documentId = new DocumentId(entityId);
                        if (match.AttributesValues.Contains("fieldsetid"))
                            documentId = new DocumentId(entityId,
                                Convert.ToInt64(match.AttributesValues["fieldsetid"].GetValue()));

                        if (!Meridian.Default.Exists(otype, entityId))
                            continue;

                        var entity = Meridian.Default.GetAs<ISphinxExportableEntity>(otype, entityId);
                        var document = entity.GetDocumentById(documentId);
                        if (document != null)
                        {
                            var item = new SphinxDocumentAnnounce(document.GetTitle(), document.GetBody(), document.GetUrl());
                            pubResult.Add(item);
                            byIndexResults[otype].Add(item);
                        }
                    }
                }

                var itemsArray = pubResult.ToArray();

                var querySplit = q.Split(' ');
                foreach (var protoIndex in protos)
                {
                    var items = byIndexResults[protoIndex];

                    if (items.Count == 0)
                        continue;

                    BuildExcerptsCommand excerptsCommand = new BuildExcerptsCommand(connection,
                        items.Select(s => s.GetBody()), querySplit, protoIndex);
                    excerptsCommand.Execute();

                    var index = 0;
                    foreach (var result in excerptsCommand.Result.Excerpts)
                    {
                        var item = items[index++];
                        item.SetBody(result);
                    }
                }

                return itemsArray;
            }
        }