public WeatherViewModel() { // if it is in designer mode, and we are not running the application if (DesignerProperties.GetIsInDesignMode(new System.Windows.DependencyObject())) { SelectedCity = new City() { LocalizedName = "Ottawa" }; CurrentConditions = new CurrentConditions() { WeatherText = "Windy", Temperature = new Temperature() { Metric = new Units { Value = "21" } } }; } SearchCommand = new SearchCommand(this); Cities = new ObservableCollection <City>(); }
public BrowserViewModel(IPackageSourceSelector packageSource, ISearchService search, IInstallService install) { Packages = new ObservableCollection <PackageViewModel>(); Search = new SearchCommand(this, packageSource, search); Paging = new PagingViewModel(Search); Install = new InstallCommand(install); }
public WeatherViewModel() { SearchCommand = new SearchCommand(this); Cities = new ObservableCollection <City>(); if (!DesignerProperties.GetIsInDesignMode(new DependencyObject())) { _accuWeatherService = App.IocContainer.Resolve <IAccuWeatherService>(); return; } City = new City { Name = "Evansville" }; CurrentConditions = new CurrentConditions { WeatherText = "Bipolar", Temperature = new Temperature { Metric = new TemperatureUnit { Value = "21" }, Imperial = new TemperatureUnit { Value = "21" } } }; }
public WeatherVM() { if (DesignerProperties.GetIsInDesignMode(new System.Windows.DependencyObject())) { SelectedCity = new City { LocalizedName = "Bhubaneswar" }; CurrentConditions = new CurrentConditions { WeatherText = "Sunny", Temperature = new Temperature { Metric = new Units { Value = "23" } } }; } SearchCommand = new SearchCommand(this); Cities = new ObservableCollection <City>(); }
public WeatherVM() { //Display data during design time, just to show data is binding to the view. if (DesignerProperties.GetIsInDesignMode(new System.Windows.DependencyObject())) { SelectedCity = new City { LocalizedName = "New York" }; CurrentConditions = new CurrentConditions { WeatherText = "Partly cloudy", Temperature = new Temperature { Imperial = new Units { Value = "65" } } }; } //Want to initialize the search command, even outside of design time. SearchCommand = new SearchCommand(this); Cities = new ObservableCollection <City>(); }
public SearchController(SearchCommand searchCommand, SearchQueryCommand searchQueryCommand, ISession session) { _searchCommand = searchCommand; _searchQueryCommand = new SearchQueryCommand(session); }
public void Search() { BookHelper bookHelper = new BookHelper(); ElasticConnection client = new ElasticConnection("222.186.190.241", 9200); //第一个参数是数据库,第二个参数是表 SearchCommand cmd = new SearchCommand("xiaoshuo", "xiaoshuo_url"); var query = new QueryBuilder <Book>() .Query(b => b.Bool(m => //并且关系 m.Must(t => //分词的最小单位或关系查询 t.QueryString(t1 => t1.DefaultField("Name").Query("总裁")) ) ) ).Size(5).Build(); var result = client.Post(cmd, query); var count = result.Result.Count(); var serializer = new JsonNetSerializer(); var results = serializer.ToSearchResult <Book>(result); //把结果序列化 Book book; foreach (var doc in results.Documents) { book = new Book() { Name = doc.Name, Url = doc.Url }; Console.WriteLine(book.Name); Console.WriteLine(book.Url); } }
void PaymentNoKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter || e.Key == Key.Return) { SearchCommand.Execute(null); } }
protected void EnqueueNextCommand(SearchCommand nextCommand) { nextCommand._coordinator = _coordinator; _coordinator._totalCommandsToExecute++; _currentCommandIndex = _coordinator._totalCommandsToExecute; _coordinator._threadPool.Enqueue(nextCommand.Execute); }
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); } )); }
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(); }); }
private void SearchModel_PropertyChanged(object sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case "ZoekBestand": if (ZoekBestand) { FolderPath = ""; } break; case "ZoekMap": if (ZoekMap) { FilePath = ""; } break; case "SearchTerm": case "FolderPath": case "FilePath": SearchCommand.RaiseCanExecuteChanged(); break; } }
private void SearchMemberKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter || e.Key == Key.Return) { SearchCommand.Execute(null); } }
public virtual IResponse <PagedSearchResults <TViewModel> > Search(string term, int page = 1, int resultsPerPage = 10) { var command = new SearchCommand <TViewModel>(term, page, resultsPerPage); var result = Dispatcher.Invoke(command); return(result); }
static void Main(string[] args) { ElasticConnection client = new ElasticConnection("localhost", 9200); SearchCommand cmd = new SearchCommand("MyTest", "persons"); var query = new QueryBuilder <Person>().Query(b => b.Bool(m => //并且关系 m.Must(t => //分词的最小单位或关系查询 t.QueryString(t1 => t1.DefaultField("Name").Query("求"))))) //分页 // .From(0) // .Size(10) ////排序 //.Sort(c => c.Field("age", SortDirection.desc)) //////添加高亮 //.Highlight(h => h // .PreTags("<b>") // .PostTags("</b>") // .Fields( // f => f.FieldName("Name").Order(HighlightOrder.score)) //) .Build(); var result = client.Post(cmd, query); var serializer = new JsonNetSerializer(); var list = serializer.ToSearchResult <Person>(result); foreach (var doc in list.Documents) { Console.WriteLine(doc.Id); } }
public WeeklyViewModel(string city) { weeklyModel = new Model.WeeklyModel(city); UserCity = city; weatherDB = weeklyModel.getWeeklyForecast(city); SearchCommand = new Command.SearchCommand(this); }
public IEnumerable <SearchResults <TResult> > MultiSearch <TResult>(IEnumerable <Tuple <SearchRequestBody, Action <SearchCommand> > > searchRequests, Action <MultiSearchCommand> commandAction) { searchRequests.ValidateNotNullOrEmptyArgument(nameof(searchRequests)); MultiSearchCommand <TResult> multiSearchCommand = this.commands.MultiSearch <TResult>(); foreach (Tuple <SearchRequestBody, Action <SearchCommand> > searchRequest in searchRequests) { SearchCommand <TResult> searchCommand = this.commands.Search <TResult>(); searchCommand.Body = searchRequest.Item1.Clone(); this.PrepareSerializerUsingConventions(searchCommand.CommandContext.Serializer); searchCommand.Indexes.Add((IndexName)this.DefaultIndex); if (searchRequest.Item2.IsNotNull()) { searchRequest.Item2((SearchCommand)searchCommand); } multiSearchCommand.SearchCommands.Add((SearchCommand)searchCommand); } if (commandAction.IsNotNull()) { commandAction((MultiSearchCommand)multiSearchCommand); } foreach (SearchResult <TResult> searchResult in multiSearchCommand.Execute()) { yield return(new SearchResults <TResult>(searchResult)); } }
public WeeklyViewModel() { weeklyModel = new Model.WeeklyModel(userCity); UserCity = "jerusalem"; weatherDB = weeklyModel.getWeeklyForecast(UserCity); SearchCommand = new Command.SearchCommand(this); }
public CustomersViewModel(MainViewModel mainView) { SelectCommand = new SelectCustomerCommand(mainView); SearchCustomersCommand = new SearchCommand(Search); AllCustomers = webService.GetAllCustomers(); CustomerResults = new ObservableCollection <Customers>(AllCustomers); }
private async Task <ImageResponse> SearchUpdateImages(string text, CancellationToken cancellationToken) { var imageResponce = await GetImagesAsync(text, cancellationToken); // _images.Clear(); _nextUrl = imageResponce.Return(x => x.NextUrl, null); if (_nextUrl == null && _lastInstagramImageId == imageResponce.MinTagId) { SearchCommand.RaiseCanExecuteChanged(); await Task.FromResult(imageResponce); } _lastInstagramImageId = imageResponce.MinTagId; foreach (var image in imageResponce.Return(x => x.Images, Enumerable.Empty <WebBrowsing.Image>())) { InstagramImageViewModel viewModel = new InstagramImageViewModel(image.Data, image.Width, image.Height, image.Url, image.FullName, image.ProfilePictureData, image.UrlAvatar, image.UserName); _images.Add(viewModel); } SearchCommand.RaiseCanExecuteChanged(); cancellationToken.ThrowIfCancellationRequested(); return(await Task.FromResult(imageResponce)); }
public WeatherVM() { if (DesignerProperties.GetIsInDesignMode(new System.Windows.DependencyObject())) { SelectedCity = new City { LocalizedName = "New York" }; CurrrentConditions = new CurrrentConditions { WeatherText = "Partly cloudy", HasPrecipitation = true, Temperature = new Temperature { Metric = new Units { Value = "21" } } }; } SearchCommand = new SearchCommand(this); Cities = new ObservableCollection <City>(); }
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 SearchResult <T> Search(SearchCommand searchCommand, QueryBuilder <T> query) { string jsonData = query.Build(); var results = connection.Post(searchCommand, jsonData); return(Serializer.ToSearchResult <T>(results)); }
// ---------------------------------------------------------------- // ---------------------------------------------------------------- public WeatherViewModel() { SearchCommand = new SearchCommand(this); Cities = new ObservableCollection <City>(); if (DesignerProperties.GetIsInDesignMode(new System.Windows.DependencyObject())) { m_SelectedCity = new City { LocalizedName = "Milwaukee" }; m_CurrentConditions = new CurrentConditions { WeatherText = "Partly cloudy", Temperature = new Temperature { Imperial = new Units { Value = 51 } } }; } }
/// <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); } } }
/// <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); } } }
private static void SearchFileContent() { var data = GetFileData(AppDomain.CurrentDomain.BaseDirectory + @"files\ccflow.doc"); var dataEncoding = Convert.ToBase64String(data); //转换为base64 ElasticSearchHelper.Intance.Index("trying-out-mapper-attachments", "person", "1", new person2() { cv = dataEncoding }); //查询文件内容 string cmd = new SearchCommand("trying-out-mapper-attachments", "person"); var query = new QueryBuilder <person2>().Query( b => b.Bool( m => m.Should( q => q.QueryString( qs => qs.Fields(new string[] { "cv" }) .Query("不支持低版本的IE浏览器") .DefaultOperator(Operator.AND))))).Build(); //文件内容查询结果 var result = Client.Post(cmd, query); JsonNetSerializer serializer = new JsonNetSerializer(); var list = serializer.ToSearchResult <person2>(result); }
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); }
/// <summary> /// Déclenche l'événement IsBusyChanged /// </summary> protected override void OnIsBusyChanged() { base.OnIsBusyChanged(); // Refresh commands SearchCommand.RaiseCanExecuteChanged(); }
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 = (string)e.SelectedItem; AvailableSugestions.Clear(); ShowHideListbox(false); if (ExecuteOnSugestionClick && SearchCommand != null && SearchCommand.CanExecute(Text)) { SearchCommand.Execute(Text); } }; AvailableSugestions = new ObservableCollection <string> (); this.ShowHideListbox(false); lstSugestions.ItemsSource = this.AvailableSugestions; //lstSugestions.ItemTemplate = this.SugestionItemDataTemplate; }
public WeatherViewModel() { // implement default constructor to display default information if (DesignerProperties.GetIsInDesignMode(new System.Windows.DependencyObject())) { SelectedCity = new City { LocalizedName = "New York" }; CurrentConditions = new CurrentConditions { WeatherText = "Partly cloudy", Temperature = new Temperature { Metric = new Units { Value = "21" } }, HasPrecipitation = true }; } SearchCommand = new SearchCommand(this); Cities = new ObservableCollection <City>(); }
static void Main(string[] args) { ElasticConnection client = new ElasticConnection("localhost", 9200); SearchCommand cmd = new SearchCommand("movies", "电影"); var query = new QueryBuilder <VerycdItem>() .Query(b => b.Bool(m => //并且关系 m.Must(t => //分词的最小单位或关系查询 t.QueryString(t1 => t1.DefaultField("content").Query("成龙")) ).Must(t => t.QueryString(t1 => t1.DefaultField("category2").Query("纪录"))) ) ).Size(100) .Build(); // DeleteCommand delCmd = new DeleteCommand() var result = client.Post(cmd, query); var serializer = new JsonNetSerializer(); var searchResult = serializer.ToSearchResult <VerycdItem>(result); //searchResult.hits.total; //一共有多少匹配结果 10500 // searchResult.Documents;//当前页的查询结果 foreach (var doc in searchResult.Documents) { Console.WriteLine(doc.title + "," + doc.category1 + "," + doc.category2); } Console.ReadKey(); }
public SearchAlbumsCommandTests() { _command = new SearchCommand(MAuth.Object, "By the throat") { Page = 2, Count = 3 }; _command.SetParameters(); }
public async Task<PageResponse<LastAlbum>> SearchAsync(string albumname, int page = 1, int itemsPerPage = LastFm.DefaultPageLength) { var command = new SearchCommand(Auth, albumname) { Page = page, Count = itemsPerPage, HttpClient = HttpClient }; return await command.ExecuteAsync(); }
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; } }
/// <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; }
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; } }
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; } }
public virtual ISearchResults Search(string scope, ISearchCriteria criteria) { var command = new SearchCommand(scope, criteria.DocumentType); command.Size(criteria.RecordsToRetrieve); command.From(criteria.StartingRecord); // Add spell checking // TODO: options.SpellCheck = new SpellCheckingParameters { Collate = true }; // Build query var builder = (QueryBuilder<ESDocument>)_queryBuilder.BuildQuery(criteria); SearchResult<ESDocument> resultDocs; // Add some error handling try { resultDocs = Client.Search(command, builder); } catch (Exception ex) { throw new ElasticSearchException("Search using Elastic Search server failed, check logs for more details.", ex); } // Parse documents returned var docList = new List<ResultDocument>(); foreach (var indexDoc in resultDocs.Documents) { var document = new ResultDocument(); foreach (var field in indexDoc.Keys) document.Add(new DocumentField(field, indexDoc[field])); docList.Add(document); } var documents = new ResultDocumentSet { TotalCount = resultDocs.hits.total, Documents = docList.OfType<IDocument>().ToArray() }; // Create search results object var results = new SearchResults(criteria, new[] { documents }) { FacetGroups = CreateFacets(criteria, resultDocs.facets) }; return results; }
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; } }
public virtual ISearchResults Search(string scope, ISearchCriteria criteria) { var command = new SearchCommand(scope, criteria.DocumentType); command.Size(criteria.RecordsToRetrieve); command.From(criteria.StartingRecord); // Add spell checking // TODO: options.SpellCheck = new SpellCheckingParameters { Collate = true }; // Build query var builder = (QueryBuilder<ESDocument>)_queryBuilder.BuildQuery(criteria); SearchResult<ESDocument> resultDocs; // Add some error handling try { resultDocs = Client.Search(command, builder); } catch (Exception ex) { throw new ElasticSearchException("Search using Elastic Search server failed, check logs for more details.", ex); } // Parse documents returned var documents = new ResultDocumentSet { TotalCount = resultDocs.hits.total }; var docList = new List<ResultDocument>(); foreach (var indexDoc in resultDocs.Documents) { var document = new ResultDocument(); foreach (var field in indexDoc.Keys) document.Add(new DocumentField(field, indexDoc[field])); docList.Add(document); } documents.Documents = docList.ToArray(); // Create search results object var results = new SearchResults(criteria, new[] { documents }); // Now add facet results var groups = new List<FacetGroup>(); if (resultDocs.facets != null) { foreach (var filter in criteria.Filters) { var groupCount = 0; var group = new FacetGroup(filter.Key); if (filter is AttributeFilter) { group.FacetType = FacetTypes.Attribute; var attributeFilter = filter as AttributeFilter; var myFilter = attributeFilter; var values = myFilter.Values; if (values != null) { var key = filter.Key.ToLower(); if (!resultDocs.facets.ContainsKey(key)) continue; var facet = resultDocs.facets[key] as TermsFacetResult; if (facet != null) { foreach (var value in values) { //facet.terms var termCount = from f in facet.terms where f.term.Equals(value.Id, StringComparison.OrdinalIgnoreCase) select f.count; var enumerable = termCount as int[] ?? termCount.ToArray(); if (!enumerable.Any()) continue; //var facet = from resultFacet var newFacet = new Facet(@group, value.Id, GetDescription(value, criteria.Locale), enumerable.SingleOrDefault()); @group.Facets.Add(newFacet); } groupCount++; } } } else if (filter is PriceRangeFilter) { group.FacetType = FacetTypes.PriceRange; var rangeFilter = filter as PriceRangeFilter; if (rangeFilter != null && rangeFilter.Currency.Equals(criteria.Currency, StringComparison.OrdinalIgnoreCase)) { var myFilter = rangeFilter; var values = myFilter.Values; if (values != null) { values = rangeFilter.Values; foreach (var value in values) { var key = String.Format("{0}-{1}", myFilter.Key, value.Id).ToLower(); if (!resultDocs.facets.ContainsKey(key)) continue; var facet = resultDocs.facets[key] as FilterFacetResult; if (facet != null && facet.count > 0) { if (facet.count == 0) continue; var myFacet = new Facet( @group, value.Id, GetDescription(value, criteria.Locale), facet.count); @group.Facets.Add(myFacet); groupCount++; } } } } } else if (filter is RangeFilter) { group.FacetType = FacetTypes.Range; var myFilter = filter as RangeFilter; if (myFilter != null) { var values = myFilter.Values; if (values != null) { foreach (var value in values) { var facet = resultDocs.facets[filter.Key] as FilterFacetResult; if (facet == null || facet.count <= 0) { continue; } var myFacet = new Facet( @group, value.Id, GetDescription(value, criteria.Locale), facet.count); @group.Facets.Add(myFacet); groupCount++; } } } } else if (filter is CategoryFilter) { group.FacetType = FacetTypes.Category; var myFilter = filter as CategoryFilter; if (myFilter != null) { var values = myFilter.Values; if (values != null) { foreach (var value in values) { var key = String.Format("{0}-{1}", myFilter.Key.ToLower(), value.Id.ToLower()).ToLower(); var facet = resultDocs.facets[key] as FilterFacetResult; if (facet == null || facet.count <= 0) { continue; } var myFacet = new Facet( @group, value.Id, GetDescription(value, criteria.Locale), facet.count); @group.Facets.Add(myFacet); groupCount++; } } } } // Add only if items exist under if (groupCount > 0) { groups.Add(group); } } } results.FacetGroups = groups.ToArray(); return results; }