// // GET: /StoreManager/ public ActionResult Index(SortField sortField = SortField.Name, SortDirection sortDirection = SortDirection.Up) { var products = db.Products.Include("Category").ToList(); var sorted = Sort(products, sortField, sortDirection); return View(sorted); }
public void SortResults(SortField sortField) { // set portal query based on sort field SetQuery(GetPortalQuery(sortField)); // refresh search results UpdateResults(); }
public void BuildWithCriteria(long countryID, long storeID, long? storeToWorldID, ViewType viewType, DateTime startDate, bool additionalManual, bool manualOnly, bool hideSums, SortField[] sortFields) { _viewType = viewType; if(startDate < DateTimeSql.DatetimeMin || startDate > DateTimeSql.DatetimeMax) { throw new ValidationException("ErrorBeginDateIncorrect", null); } if (viewType == ViewType.Weekly) { if (startDate.DayOfWeek != DayOfWeek.Monday) { throw new ValidationException("ErrorBeginDateIncorrect", null); } _startDate = startDate; _endDate = DateTimeHelper.GetSunday(startDate); } else if (viewType == ViewType.Daily) { _viewDate = startDate; _startDate = DateTimeHelper.GetMonday(startDate); _endDate = DateTimeHelper.GetSunday(startDate); } _countryID = countryID; _storeID = storeID; _sortFields = sortFields; // Use A4 landscape for single world and A3 for all worlds if (storeToWorldID.HasValue) { _storeToWorldIDs = new long[] { storeToWorldID.Value }; PaperKind = PaperKind.A4; Landscape = true; } else { PaperKind = PaperKind.A3; Landscape = false; } _additionalManual = additionalManual; _manualOnly = manualOnly; _hideSums = hideSums; PrintHeader(); LoadData(); }
private IQueryable<Product> Sort(IQueryable<Product> products, SortField sortField, SortDirection sortDirection) { if (sortField == SortField.Name) { if (sortDirection == SortDirection.Up) { return products.OrderBy(o => o.Category.Name); } else { return products.OrderByDescending(o => o.Category.Name); } } if (sortField == SortField.Price) { if (sortDirection == SortDirection.Up) { return products.OrderBy(o => o.Price); } else { return products.OrderByDescending(o => o.Price); } } if (sortField == SortField.Title) { if (sortDirection == SortDirection.Up) { return products.OrderBy(o => o.Title); } else { return products.OrderByDescending(o => o.Title); } } // Should not reach here, but return products for compiler return products; }
/// <summary> /// Initializes a new instance of the <see cref="T:Switchvox.CallQueueLogs.Search"/> class to be executed against one or more call queues /// </summary> /// <param name="startDate">The minimum date to search from.</param> /// <param name="endDate">The maximum date to search to.</param> /// <param name="queueAccountIds">A list of Call Queue Account IDs to retrieve data for. At least 1 Account ID must be specified.</param> /// <param name="callTypes">A combination of flags indicating the type of calls to include in the search results.</param> /// <param name="ignoreWeekends">Whether weekends should be excluded from the search results.</param> /// <param name="itemsPerPage">The number of results to return in this request. Additional items can be retrieved by making additional requests and incrementing the pageNumber parameter</param> /// <param name="pageNumber">The page of results to return in this request. Used in conjunction with the itemsPerPage parameter.</param> /// <param name="sortOrder">How the search results will be sorted.</param> /// <param name="sortField">The field of the search results to sort on</param> public Search(DateTime startDate, DateTime endDate, string[] queueAccountIds, CallTypes callTypes, bool ignoreWeekends = false, int itemsPerPage = 50, int pageNumber = 1, SortOrder sortOrder = SortOrder.Asc, SortField sortField = SortField.StartTime) : base("switchvox.callQueueLogs.search") { if (queueAccountIds.Length == 0) throw new ArgumentException(); List<XElement> xml = new List<XElement> { new XElement("start_date", startDate.ToString("yyyy-MM-dd HH:mm:ss")), new XElement("end_date", endDate.ToString("yyyy-MM-dd HH:mm:ss")), new XElement("ignore_weekends", Convert.ToInt32(ignoreWeekends)), new XElement("queue_account_ids", CreateAccountIdElms(queueAccountIds)), new XElement("call_types", CreateCallTypeElms(callTypes)), new XElement("sort_field", GetSortField(sortField)), new XElement("sort_order", sortOrder.ToString()), new XElement("items_per_page", itemsPerPage), new XElement("page_number", pageNumber) }; SetXml(xml); }
public static PortalQuery GetPortalQuery(SortField sortField) { switch (sortField) { case SortField.None: return PortalQuery.Default; // no sort field case SortField.HighestRated: return PortalQuery.HighestRated; //"avgrating"; case SortField.MostPopular: return PortalQuery.MostPopular; //"numviews"; case SortField.MostComments: return PortalQuery.MostComments; //"numcomments"; case SortField.Recent: return PortalQuery.Recent; //"uploaded"; case SortField.Title: return PortalQuery.Title; //"title"; case SortField.Owner: return PortalQuery.Owner; //"owner"; default: return PortalQuery.Default; } }
// // GET: /StoreManager/ public IActionResult Index(SortField sortField = SortField.Name, SortDirection sortDirection = SortDirection.Up) { // TODO [EF] Swap to native support for loading related data when available var products = from product in _db.Products join category in _db.Categories on product.CategoryId equals category.CategoryId select new Product() { ProductArtUrl = product.ProductArtUrl, ProductId = product.ProductId, CategoryId = product.CategoryId, Price = product.Price, Title = product.Title, Category = new Category() { CategoryId = product.CategoryId, Name = category.Name } }; var sorted = Sort(products, sortField, sortDirection); return View(sorted); }
private KeyValuePair<string, string>? GetSortParameter(SortField? sortField, SortOrder? sortOrder) { JsonConvert.DefaultSettings = (() => { var settings = new JsonSerializerSettings(); settings.Converters.Add(new StringEnumConverter {CamelCaseText = true}); return settings; }); if (!sortOrder.HasValue && !sortField.HasValue) return null; if (sortOrder.HasValue && sortField.HasValue) return new KeyValuePair<string, string>("sort", string.Format("{0},{1}", sortField.Value.ToRequestParameter(), sortOrder.Value.ToRequestParameter())); if (sortOrder.HasValue) return new KeyValuePair<string, string>("sort", string.Format("{0}", sortOrder.Value.ToRequestParameter())); return new KeyValuePair<string, string>("sort", string.Format("{0}", sortField.Value.ToRequestParameter())); }
public int Compare(SysFileIf x, SysFileIf y, SortField field, SortDirectrion direction) { int result = 0; switch (field) { case SortField.Name: if (direction == SortDirectrion.Ascending) { result = x.Name.CompareTo(y.Name); } else { result = y.Name.CompareTo(x.Name); } break; case SortField.Type: if (direction == SortDirectrion.Ascending) { result = x.Type.CompareTo(y.Type); } else { result = y.Type.CompareTo(x.Type); } break; case SortField.Size: if (direction == SortDirectrion.Ascending) { result = x.SizeValue.CompareTo(y.SizeValue); } else { result = y.SizeValue.CompareTo(x.SizeValue); } break; case SortField.CreateTime: if (direction == SortDirectrion.Ascending) { result = x.CreateDateTime.CompareTo(y.CreateDateTime); } else { result = y.CreateDateTime.CompareTo(x.CreateDateTime); } break; case SortField.WriteTime: if (direction == SortDirectrion.Ascending) { result = x.WriteDateTime.CompareTo(y.WriteDateTime); } else { result = y.WriteDateTime.CompareTo(x.WriteDateTime); } break; } return(result); }
public IList <HospitalModel> Search(ApiHeader apiHeader, string hospitalId, int start = GlobalConstant.StartIndex, int length = GlobalConstant.Length, string searchKeyword = null, SortField sortField = SortField.None, SortType sortType = SortType.Desc, object status = null) { throw new NotImplementedException(); }
public IList<WebRecordingBasic> GetRecordings(SortField? sort = SortField.Name, SortOrder? order = SortOrder.Asc) { return Recording.ListAll().Select(rec => rec.ToWebRecording()).SortRecordingList(sort, order).ToList(); }
public void Sort(SortField field, SortOrder order, bool recurse) { Sort(ItemPtr, field, order, recurse); }
/// <summary> /// Search for listings by tags. /// </summary> /// <param name="tags">Specify one or more tags, separated by spaces or semicolons.</param> /// <param name="sortOn">Specify the field to sort on</param> /// <param name="sortOrder">Specify the direction to sort on </param> /// <param name="offset">To page through large result sets</param> /// <param name="limit">Specify the number of results to return</param> /// <param name="detailLevel">control how much information to return</param> /// <returns>the async state of the request</returns> public IAsyncResult GetListingsByTags(IEnumerable<string> tags, SortField sortOn, SortOrder sortOrder, int offset, int limit, DetailLevel detailLevel) { if (!ServiceHelper.TestCallPrerequisites(this, this.GetListingsByTagsCompleted, this.etsyContext)) { return null; } UriBuilder uriBuilder = UriBuilder.Start(this.etsyContext, "listings/tags/") .Append(tags) .Sort(sortOn, sortOrder) .OffsetLimit(offset, limit) .DetailLevel(detailLevel); return ServiceHelper.GenerateRequest(this, uriBuilder.Result(), this.GetListingsByTagsCompleted); }
private string GetStringFromField(Document doc, SortField sortField) { var field = doc.GetField(sortField.Field); return(field == null ? "" : field.StringValue); }
/// <summary> /// Get all the listings in a shop. /// </summary> /// <param name="userName">the user name</param> /// <param name="sortOn">field to sort on</param> /// <param name="sortOrder">sort ascending or descending</param> /// <param name="sectionId">shop section to show</param> /// <param name="offset">the search results offset</param> /// <param name="limit">the search limit</param> /// <param name="detailLevel">the level of detail</param> /// <returns>the async state</returns> public IAsyncResult GetShopListings(string userName, SortField sortOn, SortOrder sortOrder, int? sectionId, int offset, int limit, DetailLevel detailLevel) { return this.wrappedService.GetShopListings(userName, sortOn, sortOrder, sectionId, offset, limit, detailLevel); }
private IQueryable <Domain.MainBoundedContext.Reports.Aggregates.Report> GetReportsByLogic(Logic logic, SortField sortField, SortOrder sortOrder, ParameterProvider parameterProvider, Int32 pageNum, Int32 pageSize) { IQueryable <Domain.MainBoundedContext.Reports.Aggregates.Report> query = _reportRepository.GetReportByLogic(logic, parameterProvider); if (sortOrder == SortOrder.ASC) { query = query.OrderBy(sortFields[sortField].GetSortExpression()); } else { query = query.OrderByDescending(sortFields[sortField].GetSortExpression()); } return(query.Skip(pageNum * pageSize).Take(pageSize)); }
private List <AppReport> GetReportsByTeam(Guid teamSiteGuid, Int32 tileId, ReportFilter filter, Boolean isCurrentUserTeamSiteAdmin, String userAlias, Int32 pageNum, Int32 pageSize, SortField sortField, SortOrder sortOrder) { #region Get the logic TileServices tService = new TileServices(_tileRepository, _teamRepository, _reportRepository, null, null, null, _tileQueryRepository); AppTile ap = null; bool hasAdminTeamSite = isCurrentUserTeamSiteAdmin; ap = tService.GetTileById(tileId); #endregion #region Combine the logic var topLevelLogic = (new TeamSiteGUID()).Equal(teamSiteGuid).And(ap.GetCombinedLogic(hasAdminTeamSite, tileId)); var logic = GenerateLogicByFilter(filter); if (logic != null) { topLevelLogic.AddElement(logic); } #endregion #region Compose the logic parameter ParameterProvider pp = new ParameterProvider(); //if (userAlias != "") //{ //pp.AddParameter(ContextVariable.CurrentUser.ToString(), userAlias); //} pp.AddParameter(ContextVariable.CurrentTeamSiteGuid.ToString(), teamSiteGuid); //if (isCurrentUserTeamSiteAdmin) //{ pp.AddParameter(ContextVariable.TeamSiteGuidUnderControl.ToString(), (new List <Guid>() { teamSiteGuid })); //} #endregion #region generate the result return(GetReportsByLogic(topLevelLogic, sortField, sortOrder, pp, pageNum, pageSize).ToArray().Select(_ => _.ToAppReport()).ToList()); #endregion }
private static IOrderedQueryable <T> SortThenBy <T>(this SortField <T> sortField, IOrderedQueryable <T> query) where T : class { return(sortField.SortOrder == SortOrder.Ascending ? query.ThenBy(sortField.PropertyName.ToExpression <T>()) : query.ThenByDescending(sortField.PropertyName.ToExpression <T>())); }
public IList<WebScheduleBasic> GetSchedulesByRange(int start, int end, SortField? sort = SortField.Name, SortOrder? order = SortOrder.Asc) { return Schedule.ListAll().Select(s => s.ToWebSchedule()).SortScheduleList(sort, order).TakeRange(start, end).ToList(); }
public IList<WebScheduleBasic> GetSchedules(SortField? sort = SortField.Name, SortOrder? order = SortOrder.Asc) { return Schedule.ListAll().Select(s => s.ToWebSchedule()).SortScheduleList(sort, order).ToList(); }
public IList<WebRecordingBasic> GetRecordingsByRange(int start, int end, SortField? sort = SortField.Name, SortOrder? order = SortOrder.Asc) { return Recording.ListAll().Select(rec => rec.ToWebRecording()).SortRecordingList(sort, order).TakeRange(start, end).ToList(); }
private List <OfferModel> DefaultSort() { _sort = SortField.DateDescending; return(Offers !.OrderByDescending(x => x.OfferDate).ToList()); }
public IList<WebChannelBasic> GetRadioChannelsBasic(int groupId, SortField? sort = SortField.User, SortOrder? order = SortOrder.Asc) { return _tvBusiness.GetRadioGuideChannelsForGroup(groupId).Select(ch => ch.ToWebChannelBasic()).SortChannelList(sort, order).ToList(); }
private void btncal_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { List <SortField> fields = new List <SortField>(); IWorkbook workbook = spreadsheetControl1.Document; Worksheet worksheet0 = workbook.Worksheets[0]; //井位信息 Worksheet worksheet1 = workbook.Worksheets[1]; //井完整性评价 Worksheet worksheet2 = workbook.Worksheets[3]; //权重 // First sorting field. First column (offset = 0) will be sorted using ascending order. SortField sortField1 = new SortField(); sortField1.ColumnOffset = 0; sortField1.Comparer = worksheet1.Comparers.Ascending; fields.Add(sortField1); // Second sorting field. Second column (offset = 1) will be sorted using ascending order. SortField sortField2 = new SortField(); sortField2.ColumnOffset = 1; sortField2.Comparer = worksheet1.Comparers.Ascending; fields.Add(sortField2); // Sort the range by sorting fields. // A rectangular range whose left column index is 0, top row index is 0, // right column index is 3 and bottom row index is 2. This is the A1:D3 cell range. int[] datanum = new int[2]; datacount(datanum, worksheet1); DevExpress.Spreadsheet.Range range = worksheet1.Range.FromLTRB(0, 1, datanum[1], datanum[0]); worksheet1.Sort(range, fields); List <double> welllocationx = new List <double>(); List <double> welllocationy = new List <double>(); List <double[]> getDatasource = new List <double[]>(); wellname = new List <string>(); //井完整性的井名 DataTimesource = new List <DateTime>(); //井完整性的时间 resultlistfen = new List <double>(); //井完整性的结果 resultlistfendraw = new List <double>(); //用于画结果图的评价结果,主要是用时间筛选 wellnamedraw = new List <string>(); //用于画结果图的井名 List <double> result = new List <double>(); List <double> weightData = new List <double>(); List <string> wellfullname = new List <string>(); int countcol = importdata(getDatasource, DataTimesource, wellname, worksheet1); //井完整性评价 importdata(weightData, worksheet2); //权重 importdata(welllocationx, welllocationy, wellfullname, worksheet0); //井坐标 List <double> topten = new List <double>(); for (int i = 0; i < getDatasource.Count; i++) { List <double> tempdata = new List <double>(); for (int j = 0; j < countcol; j++) { tempdata.Add(getDatasource[i][j]); } tempdata.Sort(); topten.Add(tempdata[(int)(tempdata.Count * 0.1)]); } for (int i = 0; i < getDatasource.Count; i++) { double temp = 0; double temp2 = 0; for (int j = 0; j < countcol; j++) { temp = temp + getDatasource[i][j] * weightData[j]; } if (temp < 6) { temp2 = 0; worksheet1.Cells[i + 1, countcol + 3].Value = "安全"; } else if (temp < 7) { temp2 = 1; worksheet1.Cells[i + 1, countcol + 3].Value = "较安全"; } else if (temp < 8) { temp2 = 2; worksheet1.Cells[i + 1, countcol + 3].Value = "中等"; } else if (temp < 9) { temp2 = 3; worksheet1.Cells[i + 1, countcol + 3].Value = "较危险"; string ss = ""; for (int j = 0; j < countcol; j++) { if (getDatasource[i][j] > topten[j]) { ss = "2"; } } } else { temp2 = 4; worksheet1.Cells[i + 1, countcol + 3].Value = "危险"; } resultlistfen.Add(temp2); worksheet1.Cells[i + 1, countcol + 2].Value = temp; //worksheet2.Visible = false; } worksheet1.Cells[0, countcol + 2].Value = "综合得分"; worksheet1.Cells[0, countcol + 3].Value = "评价结果"; listdate = DataTimesource.Distinct().ToList(); for (int i = 0; i < listdate.Count; i++) { (timeselect.Edit as RepositoryItemComboBox).Items.Add(listdate[i].ToShortDateString()); } timeselect.EditValue = (timeselect.Edit as RepositoryItemComboBox).Items[0]; adddraw(wellfullname, welllocationx, welllocationy); adddraw2(listdate[0].ToShortDateString() + "井筒完整性评价结果图"); //ComboBoxproperties.Items.AddRange for (int i = 0; i < DataTimesource.Count; i++) { if (DataTimesource[i] == listdate[0]) { resultlistfendraw.Add(resultlistfen[i]); // = new List<double>();//用于画结果图的评价结果,主要是用时间筛选 wellnamedraw.Add(wellname[i]); // = new List<string>();//用于画结果图的井名 } } }
public IList<WebChannelDetailed> GetChannelsDetailed(int groupId, SortField? sort = SortField.User, SortOrder? order = SortOrder.Asc) { return _tvBusiness.GetTVGuideChannelsForGroup(groupId).Select(ch => ch.ToWebChannelDetailed()).SortChannelList(sort, order).ToList(); }
public MyOrderDetailFilter() { Id = new SortField <int>(SortMode.Desc); }
/// <summary> /// Search for listings by category. /// </summary> /// <param name="category">the category name</param> /// <param name="sortOn">Specify the field to sort on</param> /// <param name="sortOrder">Specify the direction to sort on</param> /// <param name="offset">To page through large result sets</param> /// <param name="limit">Specify the number of results to return</param> /// <param name="detailLevel">control how much information to return</param> /// <returns>the async state of the request</returns> public IAsyncResult GetListingsByCategory(string category, SortField sortOn, SortOrder sortOrder, int offset, int limit, DetailLevel detailLevel) { if (!ServiceHelper.TestCallPrerequisites(this, this.GetListingsByCategoryCompleted, this.etsyContext)) { return null; } UriBuilder uriBuilder = UriBuilder.Start(this.etsyContext, "listings/category", category) .Sort(sortOn, sortOrder) .OffsetLimit(offset, limit) .DetailLevel(detailLevel); return ServiceHelper.GenerateRequest(this, uriBuilder.Result(), this.GetListingsByCategoryCompleted); }
public IList <ClinicResult> Search(ApiHeader apiHeader, string hospitalId, int start = 0, int length = int.MaxValue, string searchKeyword = null, SortField sortField = SortField.None, SortType sortType = SortType.Desc, object status = null) { throw new NotImplementedException(); }
public void TestSearchAfterWhenSortingByFunctionValues() { Directory dir = NewDirectory(); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, null); iwc.SetMergePolicy(NewLogMergePolicy()); // depends on docid order RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, iwc); Document doc = new Document(); Field field = new StringField("value", "", Field.Store.YES); doc.Add(field); // Save docs unsorted (decreasing value n, n-1, ...) const int NUM_VALS = 5; for (int val = NUM_VALS; val > 0; val--) { field.StringValue = Convert.ToString(val); writer.AddDocument(doc); } // Open index IndexReader reader = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(reader); // Get ValueSource from FieldCache IntFieldSource src = new IntFieldSource("value"); // ...and make it a sort criterion SortField sf = src.GetSortField(false).Rewrite(searcher); Sort orderBy = new Sort(sf); // Get hits sorted by our FunctionValues (ascending values) Query q = new MatchAllDocsQuery(); TopDocs hits = searcher.Search(q, reader.MaxDoc, orderBy); assertEquals(NUM_VALS, hits.ScoreDocs.Length); // Verify that sorting works in general int i = 0; foreach (ScoreDoc hit in hits.ScoreDocs) { int valueFromDoc = Convert.ToInt32(reader.Document(hit.Doc).Get("value")); assertEquals(++i, valueFromDoc); } // Now get hits after hit #2 using IS.searchAfter() int afterIdx = 1; FieldDoc afterHit = (FieldDoc)hits.ScoreDocs[afterIdx]; hits = searcher.SearchAfter(afterHit, q, reader.MaxDoc, orderBy); // Expected # of hits: NUM_VALS - 2 assertEquals(NUM_VALS - (afterIdx + 1), hits.ScoreDocs.Length); // Verify that hits are actually "after" int afterValue = (int)((double?)afterHit.Fields[0]); foreach (ScoreDoc hit in hits.ScoreDocs) { int val = Convert.ToInt32(reader.Document(hit.Doc).Get("value")); assertTrue(afterValue <= val); assertFalse(hit.Doc == afterHit.Doc); } reader.Dispose(); dir.Dispose(); }
/// <summary> /// 获取分页信息 /// </summary> /// <returns></returns> public List <Cost> GetPageList(int pageSize, int pageIndex, List <QueryField> queryList, SortField sort, out int recordCount) { List <Cost> li = new Repository <Cost>().GetList(pageSize, pageIndex, queryList, sort, out recordCount) as List <Cost>; return(li); }
private Sort GetSortCriteria(string sortByField = null) { if (String.IsNullOrWhiteSpace(sortByField)) return Sort.RELEVANCE; var fieldName = sortByField.Trim().TrimStart('+'); var isDescending = fieldName.StartsWith("-", StringComparison.InvariantCulture); if (isDescending) fieldName = fieldName.TrimStart('-'); var sortBySchemaField = Schema.FindField(fieldName, false); if (sortBySchemaField == null) throw new LuceneQueryParserException($"Invalid sortBy field: '{fieldName}'."); // Notes: // 1. The actual sort fieldname is different, e.g. 'fieldName' ==> '__fieldName_sort__' // 2. If a document does not have a value for the sort field, a default 'missing value' is assigned // so that the document always appears last in the resultset. var sortFieldName = fieldName.ToSortFieldName(); SortField sortField = null; switch (sortBySchemaField.DataType) { case Schema.DataType.Number: sortField = new SortField(sortFieldName, SortFieldType.DOUBLE, isDescending); sortField.SetMissingValue(isDescending ? LuceneUtils.DOUBLE_MIN_VALUE : LuceneUtils.DOUBLE_MAX_VALUE); break; case Schema.DataType.DateTime: case Schema.DataType.Boolean: sortField = new SortField(sortFieldName, SortFieldType.LONG, isDescending); sortField.SetMissingValue(isDescending ? LuceneUtils.LONG_MIN_VALUE : LuceneUtils.LONG_MAX_VALUE); break; case Schema.DataType.Text: case Schema.DataType.Guid: sortField = new SortField(sortFieldName, SortFieldType.STRING, isDescending); sortField.SetMissingValue(isDescending ? SortField.STRING_FIRST : SortField.STRING_LAST ); break; default: throw new LuceneQueryParserException($"Invalid sortBy field: '{fieldName}'. Only Number, DateTime, Boolean, Text, and GUID fields can be used for sorting."); } if (sortField == null) return Sort.RELEVANCE; else return new Sort(new[] { sortField }); }
/// <summary> /// 获取翻页一览 /// </summary> /// <param name="pageSize"></param> /// <param name="pageIndex"></param> /// <param name="queryList"></param> /// <param name="sort"></param> /// <param name="recordCount"></param> /// <returns></returns> public virtual IList <T> GetList(int pageSize, int pageIndex, List <QueryField> queryList, SortField sort, out int recordCount) { int startIndex = pageSize * (pageIndex - 1); ICriteria crit = Session.CreateCriteria <T>(); if (queryList != null) { foreach (var query in queryList) { crit.Add(GetExpression(query)); } } // Copy current ICriteria instance to the new one for getting the pagination records. ICriteria pageCrit = CriteriaTransformer.Clone(crit); // Get the total record count recordCount = Convert.ToInt32(pageCrit.SetProjection(Projections.RowCount()).UniqueResult()); if (sort != null) { crit.AddOrder(GetOrder(sort)); } return(crit.SetFirstResult(startIndex) .SetMaxResults(pageSize) .List <T>()); }
private IDisposable GetSort(IndexQueryServerSide query, Index index, Func <string, SpatialField> getSpatialField, DocumentsOperationContext documentsContext, out Sort sort) { sort = null; if (query.PageSize == 0) // no need to sort when counting only { return(null); } var orderByFields = query.Metadata.OrderBy; if (orderByFields == null) { if (query.Metadata.HasBoost == false && index.HasBoostedFields == false) { return(null); } sort = SortByFieldScore; return(null); } int sortIndex = 0; var sortArray = new ArraySegment <SortField>(ArrayPool <SortField> .Shared.Rent(orderByFields.Length), sortIndex, orderByFields.Length); foreach (var field in orderByFields) { if (field.OrderingType == OrderByFieldType.Random) { string value = null; if (field.Arguments != null && field.Arguments.Length > 0) { value = field.Arguments[0].NameOrValue; } sortArray[sortIndex++] = new RandomSortField(value); continue; } if (field.OrderingType == OrderByFieldType.Score) { if (field.Ascending) { sortArray[sortIndex++] = SortField.FIELD_SCORE; } else { sortArray[sortIndex++] = new SortField(null, 0, true); } continue; } if (field.OrderingType == OrderByFieldType.Distance) { var spatialField = getSpatialField(field.Name); int lastArgument; Point point; switch (field.Method) { case MethodType.Spatial_Circle: var cLatitude = field.Arguments[1].GetDouble(query.QueryParameters); var cLongitude = field.Arguments[2].GetDouble(query.QueryParameters); lastArgument = 2; point = spatialField.ReadPoint(cLatitude, cLongitude).GetCenter(); break; case MethodType.Spatial_Wkt: var wkt = field.Arguments[0].GetString(query.QueryParameters); SpatialUnits?spatialUnits = null; lastArgument = 1; if (field.Arguments.Length > 1) { spatialUnits = Enum.Parse <SpatialUnits>(field.Arguments[1].GetString(query.QueryParameters), ignoreCase: true); lastArgument = 2; } point = spatialField.ReadShape(wkt, spatialUnits).GetCenter(); break; case MethodType.Spatial_Point: var pLatitude = field.Arguments[0].GetDouble(query.QueryParameters); var pLongitude = field.Arguments[1].GetDouble(query.QueryParameters); lastArgument = 2; point = spatialField.ReadPoint(pLatitude, pLongitude).GetCenter(); break; default: throw new ArgumentOutOfRangeException(); } var roundTo = field.Arguments.Length > lastArgument ? field.Arguments[lastArgument].GetDouble(query.QueryParameters) : 0; var dsort = new SpatialDistanceFieldComparatorSource(spatialField, point, query, roundTo); sortArray[sortIndex++] = new SortField(field.Name, dsort, field.Ascending == false); continue; } var fieldName = field.Name.Value; var sortOptions = SortField.STRING; switch (field.OrderingType) { case OrderByFieldType.Custom: var cName = field.Arguments[0].NameOrValue; var cSort = new CustomComparatorSource(cName, _index.DocumentDatabase.Name, query); sortArray[sortIndex++] = new SortField(fieldName, cSort, field.Ascending == false); continue; case OrderByFieldType.AlphaNumeric: var anSort = new AlphaNumericComparatorSource(documentsContext); sortArray[sortIndex++] = new SortField(fieldName, anSort, field.Ascending == false); continue; case OrderByFieldType.Long: sortOptions = SortField.LONG; fieldName += Constants.Documents.Indexing.Fields.RangeFieldSuffixLong; break; case OrderByFieldType.Double: sortOptions = SortField.DOUBLE; fieldName += Constants.Documents.Indexing.Fields.RangeFieldSuffixDouble; break; } sortArray[sortIndex++] = new SortField(fieldName, sortOptions, field.Ascending == false); } sort = new Sort(sortArray); return(new ReturnSort(sortArray)); }
public void Visit(SortField component) { throw new NotImplementedException(); }
public void Visit(SortField component) { component.Field.Accept(this); sql.Append(component.Descending ? " DESC" : " ASC"); }
/// <summary> ///根据关键字进行查询,根据int的范围进行搜索 /// </summary> /// <param name="Title"></param> /// <returns></returns> public List <Bpo_JobEntity> SearchJobList4(string Title, string FullAddress, int MinId, int MaxId) { List <Bpo_JobEntity> jobList = new List <Bpo_JobEntity>(); string path = "F://LuceneIndexDir"; FSDirectory dir = FSDirectory.Open(path); //IndexSearcher searcher = new IndexSearcher(dir);//声明一个查询器,或者以下面一种方式声明 IndexReader reader = IndexReader.Open(dir, true);//查询器 IndexSearcher searcher = new IndexSearcher(reader); //搜索条件,BooleanQuery可以同时制定多个搜索条件 BooleanQuery booleanQuery = new BooleanQuery(); //Query query = new TermQuery(new Term("Title", $"*{Title}*"));//不支持通配符 //Query query = new WildcardQuery(new Term("Title", $"*{Title}*")); // 通配符 if (!string.IsNullOrEmpty(Title))//空格隔开,按照多个词进行搜索 { Title = new LuceneAnalyze().AnalyzerKeyword("Title", Title); QueryParser parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, "Title", new PanGuAnalyzer()); Query query = parser.Parse(Title); booleanQuery.Add(query, Occur.MUST); } if (MinId > 0)//空格隔开,按照多个词进行搜索 { //string idStr = new LuceneAnalyze().AnalyzerKeyword("Id", MinId.ToString()); QueryParser parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, "Id", new PanGuAnalyzer()); Query query = parser.Parse(MinId.ToString()); booleanQuery.Add(query, Occur.MUST); } if (!string.IsNullOrEmpty(FullAddress)) { FullAddress = new LuceneAnalyze().AnalyzerKeyword("FullAddress", FullAddress); QueryParser parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, "FullAddress", new PanGuAnalyzer()); Query query = parser.Parse(FullAddress); booleanQuery.Add(query, Occur.MUST); //使用WildcardQuery,相当于sql的like //Query query2 = new WildcardQuery(new Term("FullAddress", $"*{FullAddress}*")); // 通配符 //booleanQuery.Add(query2, Occur.MUST); } //根据id区间区间搜索(此时id存储索引时要是NumericField类型) NumericRangeFilter <int> intFilter = null; //if (MinId > 0 && MaxId == 0) //{ // intFilter = NumericRangeFilter.NewIntRange("Id", MinId, int.MaxValue, true, true); //} //else if (MaxId > 0 && MinId == 0) //{ // intFilter = NumericRangeFilter.NewIntRange("Id", 0, MaxId, true, true); //} //else if (MaxId > 0 && MinId > 0) //{ // intFilter = NumericRangeFilter.NewIntRange("Id", MinId, MaxId, true, true); //} //定义排序 SortField sortField = new SortField("Id", SortField.STRING, false); //降序 SortField sortField2 = new SortField("CompanyId", SortField.INT, false); //降序 Sort sort = new Sort(sortField, sortField2); //取搜索结果方法1: TopDocs docs = searcher.Search(booleanQuery, intFilter, 10000, sort); //找到的结果取100条数据 foreach (ScoreDoc sd in docs.ScoreDocs) //从docs.ScoreDocs取数据 { Document doc = searcher.Doc(sd.Doc); jobList.Add(new Bpo_JobEntity { Id = Convert.ToInt32(doc.Get("Id") ?? "-100"), Title = doc.Get("Title"), UserId = Convert.ToInt32(doc.Get("UserId") ?? "-100"), UserName = doc.Get("UserName"), CompanyId = Convert.ToInt32(doc.Get("CompanyId") ?? "-100"), CompanyName = doc.Get("CompanyName"), FullAddress = doc.Get("FullAddress"), CreateDate = Convert.ToDateTime(doc.Get("CreateDate")) }); } return(jobList); }
public void AddGridToCollection(DBSNAPGridView sdg, DataGridNameCollection thispage_dgnc) { // is it already in the collection ? //if not, create a new datagridcouple and add it to the collection if (!IsDGNinDGNC(sdg.ID, thispage_dgnc)) { DataGridControl dc = new DataGridControl(); dc.GridName = sdg.ID; dc.ViewSource = sdg.ViewSource; dc.ActionTarget = sdg.ActionTarget; dc.SQLB.Distinct = sdg.Distinct; if (sdg.AllowPaging) { dc.SQLB.PageIndex = sdg.PageIndex; dc.SQLB.PageSize = sdg.PageSize; } else { dc.SQLB.PageSize = -1; } //setting the keyfields in the SQLB of the dc string[] keyfields = sdg.PrimaryKey.Split(','); foreach (string keyfield in keyfields) { string kf = keyfield.Trim(); DataField dfield = new DataField(); dfield.Name = kf; dfield.PKField = true; dc.SQLB.DataFields.Add(dfield); } dc.ParentControl = sdg.ParentControl; dc.ParentKeyExpression = sdg.ParentKeyExpression; //setting the parentkey fields as filters //getting the keys if (dc.ParentKeyExpression != null && dc.ParentKeyExpression != "") { string[] parentkeys = sdg.ParentKeyExpression.Split(','); foreach (string parentkey in parentkeys) { string[] keys = parentkey.Split('='); FilterField ffield = new FilterField(); ffield.Name = keys[1].Trim(); ffield.FilterType = snpFilterType.Equal; // ffield.Value = keys[0].Trim(); ffield.ParentKey = true; dc.SQLB.FilterFields.Add(ffield); } } //putting in the datagrid columns as datafields DataControlFieldCollection cols = sdg.Columns; foreach (DataControlField col in cols) { string dfieldname = string.Empty; try { Type t = col.GetType(); dfieldname = (string)t.InvokeMember("DataField", System.Reflection.BindingFlags.GetProperty, null, col, new object[] { }); } catch { } if (dfieldname != string.Empty || dfieldname.Trim() != string.Empty) { DataField dfield = new DataField(); dfield.Name = dfieldname.Trim(); dc.SQLB.DataFields.Add(dfield); } } //setting the sortfields in the SQLB of the dc string[] sortfields = sdg.OrderBy.Split(','); foreach (string sortfield in sortfields) { string sf = sortfield.Trim(); string[] sfe = sf.Split(' '); string sfe0 = sfe[0] == null || sfe[0] == "" ? "" : sfe[0].Trim(); if (sfe0 != "") { SortField sfield = new SortField(); sfield.Name = sfe0; string sfe1 = sfe[1] == null || sfe[1] == "" ? "" : sfe[1].Trim(); if (sfe1 != "") { sfe1 = sfe1.ToUpper(); if (sfe1 == "ASC") { sfield.Order = snpOrder.ASC; } else { sfield.Order = snpOrder.DESC; } } dc.SQLB.SortFields.Add(sfield); } } dc.GridPage = sdg.Page.ToString(); dc.OnPage = true; thispage_dgnc.Add(dc); //also adding the parentdatagrid //this is necessary for 2 reasons : //-sorting the grids //-also, when there are no controls on the page if (dc.ParentControl != null && dc.ParentControl != "") { AddParentControl(sdg.Page, dc, thispage_dgnc); } } }
/// ------------------------------------------------------------------------------------ internal NodeComparer(string srcLangId, string tgtLangId, SortOrder sortOrder, SortField sortField) { _srcLangId = srcLangId; _tgtLangId = tgtLangId; _sortOrder = sortOrder; _sortField = sortField; }
public void DeserialiseSearchResultJson_SortFieldNotNull_ReturnsSortFieldEnum(SortField expectedValue, string sortFieldJson) { string sampleJson = $"{{\"foodSearchCriteria\":{{\"sortField\":\"{sortFieldJson}\"}}}}"; SearchResult searchResult = JsonConvert.DeserializeObject <SearchResult>(sampleJson); Assert.Equal(expectedValue, searchResult.FoodSearchCriteria.SortField); }
public static void Show() { FSDirectory dir = FSDirectory.Open(StaticConstant.TestIndexPath); IndexSearcher searcher = new IndexSearcher(dir); //查找器 { TermQuery query = new TermQuery(new Term("title", "图书馆")); //包含 TopDocs docs = searcher.Search(query, null, 10000); //找到的数据 foreach (ScoreDoc sd in docs.ScoreDocs) { Document doc = searcher.Doc(sd.Doc); Console.WriteLine("***************************************"); Console.WriteLine(string.Format("id={0}", doc.Get("id"))); Console.WriteLine(string.Format("title={0}", doc.Get("title"))); Console.WriteLine(string.Format("time={0}", doc.Get("time"))); Console.WriteLine(string.Format("price={0}", doc.Get("price"))); Console.WriteLine(string.Format("content={0}", doc.Get("content"))); } Console.WriteLine("1一共命中了{0}个", docs.TotalHits); } QueryParser parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, "title", new PanGuAnalyzer());//解析器 { //string keyword = "高中政治人教新课标选修生活中的法律常识"; string keyword = "高中政治 人 教 新课 标 选修 生活 中的 法律常识"; { Query query = parser.Parse(keyword); TopDocs docs = searcher.Search(query, null, 10000);//找到的数据 int i = 0; foreach (ScoreDoc sd in docs.ScoreDocs) { if (i++ < 1000) { Document doc = searcher.Doc(sd.Doc); Console.WriteLine("***************************************"); Console.WriteLine(string.Format("id={0}", doc.Get("id"))); Console.WriteLine(string.Format("title={0}", doc.Get("title"))); Console.WriteLine(string.Format("time={0}", doc.Get("time"))); Console.WriteLine(string.Format("price={0}", doc.Get("price"))); } } Console.WriteLine($"一共命中{docs.TotalHits}"); } { Query query = parser.Parse(keyword); NumericRangeFilter <int> timeFilter = NumericRangeFilter.NewIntRange("time", 20190101, 20191231, true, true); //过滤 SortField sortPrice = new SortField("price", SortField.DOUBLE, false); //降序 SortField sortTime = new SortField("time", SortField.INT, true); //升序 Sort sort = new Sort(sortTime, sortPrice); //排序 哪个前哪个后 TopDocs docs = searcher.Search(query, timeFilter, 10000, sort); //找到的数据 int i = 0; foreach (ScoreDoc sd in docs.ScoreDocs) { if (i++ < 1000) { Document doc = searcher.Doc(sd.Doc); Console.WriteLine("***************************************"); Console.WriteLine(string.Format("id={0}", doc.Get("id"))); Console.WriteLine(string.Format("title={0}", doc.Get("title"))); Console.WriteLine(string.Format("time={0}", doc.Get("time"))); Console.WriteLine(string.Format("price={0}", doc.Get("price"))); } } Console.WriteLine("3一共命中了{0}个", docs.TotalHits); } } }
public SymbolsListComparer(int displayIndex, bool isAscending) { Debug.Assert(displayIndex >= 0 && displayIndex <= 4); mIsAscending = isAscending; mSortField = (SortField)displayIndex; }
/// <summary> /// 产品搜索 /// 从索引 /// </summary> /// <param name="key">搜索关键字</param> /// <param name="categorySysNo">分类编号</param> /// <param name="attributes">属性列表</param> /// <param name="pageIndex">页码</param> /// <param name="pageSize">页大小</param> /// <param name="pageCount">分页总数</param> /// <param name="recCount">总记录数</param> /// <param name="highLight">是否高亮关键字</param> /// <param name="sort">排序(0:相关度 1:销量 2:价格 3:评分 4:上架时间)</param> /// <param name="isDescending">true 为降序 false为升序</param> /// <param name="productSysNo">商品编号</param> /// <param name="priceSource">产品价格来源</param> /// <param name="priceSourceSysNo">产品价格来源编号(会员等级编号)</param> /// <param name="showNotFrontEndOrder">搜索前台不能下单的商品(2014-2-14 黄波 添加 物流APP需要)</param> /// <returns>商品列表</returns> /// <remarks>2013-08-08 黄波 创建</remarks> /// <remarks>2013-11-12 邵斌 修改 添加搜索商品系统编号:该方法暂时闲置</remarks> /// <remarks>2013-12-23 邵斌 添加前台是否下单字段</remarks> /// <remarks>2014-02-14 黄波 添加是否搜索前台不能下单的商品(物流APP需要)</remarks> public IList <PdProductIndex> Search(string key , int?categorySysNo , List <int> attributes , int pageSize , ref int pageIndex , ref int pageCount , ref int recCount , bool highLight = false , int sort = 1 , bool isDescending = false , int productSysNo = 0 , ProductStatus.产品价格来源 priceSource = ProductStatus.产品价格来源.会员等级价 , int priceSourceSysNo = CustomerLevel.初级 , bool showNotFrontEndOrder = false) { var returnValue = new List <PdProductIndex>(); var indexSearch = Hyt.Infrastructure.Lucene.ProductIndex.Searcher; try { pageIndex = pageIndex == 0 ? 1 : pageIndex; key = key ?? ""; //查询设置初始值 #region 搜索条件 BooleanQuery query = new BooleanQuery(); BooleanQuery childQuery; BooleanQuery esenQuery; #region 关键字搜索 string keywords = key.Trim(); if (!string.IsNullOrWhiteSpace(keywords)) { childQuery = new BooleanQuery(); esenQuery = new BooleanQuery(); if (!IsErpCode(keywords)) { ////全词去空格 //esenQuery.Add(new TermQuery(new Term("ProductName", Regex.Replace(keywords, @"\s", ""))), // BooleanClause.Occur.SHOULD); //esenQuery.SetBoost(3.0F); //esenQuery.Add(new TermQuery(new Term("ProductSubName", Regex.Replace(keywords, @"\s", ""))), // BooleanClause.Occur.SHOULD); //esenQuery.SetBoost(3.0F); //childQuery.Add(esenQuery, BooleanClause.Occur.SHOULD); esenQuery = new BooleanQuery(); //分词 盘古分词 var keyWordsSplitBySpace = GetKeyWordsSplitBySpace(keywords); if (string.IsNullOrWhiteSpace(keyWordsSplitBySpace)) { return(null); } keyWordsSplitBySpace = string.Format("{0}^{1}.0", keywords, (int)Math.Pow(3, 5)); QueryParser productNameQueryParser = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "ProductName", new PanGuAnalyzer(true)); Query productNameQuery = productNameQueryParser.Parse(keyWordsSplitBySpace); childQuery.Add(productNameQuery, BooleanClause.Occur.SHOULD); //以什么开头,输入“ja”就可以搜到包含java和javascript两项结果了 Query prefixQuery_productName = new PrefixQuery(new Term("ProductName", key)); //直接模糊匹配,假设你想搜索跟‘wuzza’相似的词语,你可能得到‘fuzzy’和‘wuzzy’。 Query fuzzyQuery_productName = new FuzzyQuery(new Term("ProductName", key)); //通配符搜索 Query wildcardQuery_productName = new WildcardQuery(new Term("ProductName", string.Format("*{0}*", key.Trim()))); childQuery.Add(prefixQuery_productName, BooleanClause.Occur.SHOULD); childQuery.Add(fuzzyQuery_productName, BooleanClause.Occur.SHOULD); childQuery.Add(wildcardQuery_productName, BooleanClause.Occur.SHOULD); //esenQuery.Add(new QueryParser("ProductName", new PanGuAnalyzer(true)).Parse(keyWordsSplitBySpace), BooleanClause.Occur.SHOULD); //esenQuery.Add(new QueryParser("ProductSubName", new PanGuAnalyzer(true)).Parse(keyWordsSplitBySpace), BooleanClause.Occur.SHOULD); ////分词 按空格 //var keyColl = keywords.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); //foreach (var item in keyColl) //{ // esenQuery.Add(new TermQuery(new Term("ProductName", item)), // BooleanClause.Occur.SHOULD); // esenQuery.Add(new TermQuery(new Term("ProductSubName", item)), // BooleanClause.Occur.SHOULD); //} //esenQuery.SetBoost(2.9F); //childQuery.Add(esenQuery, BooleanClause.Occur.SHOULD); } else { esenQuery.Add(new TermQuery(new Term("ErpCode", Regex.Replace(keywords, @"\s", ""))), BooleanClause.Occur.SHOULD); esenQuery.SetBoost(3.0F); childQuery.Add(esenQuery, BooleanClause.Occur.SHOULD); } query.Add(childQuery, BooleanClause.Occur.MUST); } #endregion #region 分类搜索 if (categorySysNo.HasValue && categorySysNo.Value != 0) { childQuery = new BooleanQuery(); esenQuery = new BooleanQuery(); esenQuery.Add(new TermQuery(new Term("Category", categorySysNo.Value.ToString())), BooleanClause.Occur.SHOULD); esenQuery.SetBoost(3.0F); childQuery.Add(esenQuery, BooleanClause.Occur.SHOULD); esenQuery = new BooleanQuery(); esenQuery.Add(new WildcardQuery(new Term("AssociationCategory", string.Format("*,{0},*", categorySysNo.Value.ToString()))), BooleanClause.Occur.SHOULD); esenQuery.SetBoost(2.8F); childQuery.Add(esenQuery, BooleanClause.Occur.SHOULD); //所有子分类 var childCategoryList = Hyt.BLL.Web.PdCategoryBo.Instance.GetChildAllCategory(categorySysNo.Value); foreach (var item in childCategoryList) { esenQuery = new BooleanQuery(); esenQuery.Add(new TermQuery(new Term("Category", item.SysNo.ToString())), BooleanClause.Occur.SHOULD); esenQuery.SetBoost(3.0F); childQuery.Add(esenQuery, BooleanClause.Occur.SHOULD); esenQuery = new BooleanQuery(); esenQuery.Add(new WildcardQuery(new Term("AssociationCategory", string.Format("*,{0},*", item.SysNo.ToString()))), BooleanClause.Occur.SHOULD); childQuery.Add(esenQuery, BooleanClause.Occur.SHOULD); } query.Add(childQuery, BooleanClause.Occur.MUST); } #endregion #region 属性搜索 if (attributes != null) { childQuery = new BooleanQuery(); esenQuery = new BooleanQuery(); foreach (var item in attributes) { esenQuery.Add(new WildcardQuery(new Term("Attributes", string.Format("*,*:{0},*", item.ToString()))), BooleanClause.Occur.MUST); } childQuery.Add(esenQuery, BooleanClause.Occur.MUST); query.Add(childQuery, BooleanClause.Occur.MUST); } #endregion #region 品牌搜索 //if (brandSysNo.Value != 0) //{ // childQuery = new BooleanQuery(); // childQuery.Add(new TermQuery(new Term("BrandSysNo", brandSysNo.Value.ToString())), // BooleanClause.Occur.SHOULD); // childQuery.SetBoost(3.0F); // query.Add(childQuery, BooleanClause.Occur.MUST); //} #endregion #region 仅搜索有效的商品 childQuery = new BooleanQuery(); childQuery.Add(new TermQuery(new Term("Status", ((int)Hyt.Model.WorkflowStatus.ProductStatus.产品上线状态.效).ToString())), BooleanClause.Occur.SHOULD); query.Add(childQuery, BooleanClause.Occur.MUST); //2013-12-23 邵斌 添加前台是否下单字段 if (!showNotFrontEndOrder) { childQuery = new BooleanQuery(); childQuery.Add(new TermQuery(new Term("CanFrontEndOrder", ((int)Hyt.Model.WorkflowStatus.ProductStatus.商品是否前台下单.是).ToString())), BooleanClause.Occur.SHOULD); query.Add(childQuery, BooleanClause.Occur.MUST); } #endregion #region 排序 //isDescending true为降序 false为升序 SortField sf = null; switch (Math.Abs(sort)) { case 1: //销量 sf = new SortField("SalesCount", SortField.INT, isDescending); break; case 2: //价格 sf = new SortField("BasicPrice", SortField.FLOAT, isDescending); break; case 3: //评分 sf = new SortField("CommentCount", SortField.INT, isDescending); break; case 4: //上架时间 sf = new SortField("CreatedDate", SortField.STRING, isDescending); break; default: sf = new SortField(null, SortField.SCORE, false); break; } Sort luceneSort; //排序对象 //默认匹配度,表明是对固定信息进行搜索,所以就要进行先安匹配度来排序。这样用户搜索的商品将排在前面,方便用户筛选 if (Math.Abs(sort) != (int)CommonEnum.LuceneProductSortType.默认匹配度) { //无搜索关键字的时候就按模式设置的进行排序 luceneSort = new Sort(); luceneSort.SetSort(sf); } else { //收搜索关键字时,就要先安匹配度进行排序,然后才是设置排序。 luceneSort = new Sort(new SortField[] { SortField.FIELD_SCORE, sf }); } #endregion #region 商品系统编号搜索 if (productSysNo > 0) { childQuery = new BooleanQuery(); esenQuery = new BooleanQuery(); esenQuery.Add(new TermQuery(new Term("SysNo", productSysNo.ToString())), BooleanClause.Occur.SHOULD); esenQuery.SetBoost(3.0F); childQuery.Add(esenQuery, BooleanClause.Occur.SHOULD); query.Add(childQuery, BooleanClause.Occur.MUST); } #endregion #endregion Hits hits = indexSearch.Search(query, luceneSort); recCount = hits.Length(); pageCount = (int)Math.Ceiling((double)recCount / (double)pageSize); if (pageIndex <= 0) { pageIndex = 1; } if (pageIndex > pageCount) { pageIndex = pageCount; } var recordIndex = Math.Max((pageIndex - 1) * pageSize, 0); PdProductIndex pdProductIndex; var simpleHtmlFormatter = new PanGu.HighLight.SimpleHTMLFormatter("<font color=\"red\">", "</font>"); var T_ProductName = ""; while (recordIndex < recCount && returnValue.Count < pageSize) { try { pdProductIndex = Hyt.Infrastructure.Lucene.ProductIndex.Instance.DocumentToModel(hits.Doc(recordIndex)); string productName = pdProductIndex.ProductName; if (highLight && !string.IsNullOrEmpty(key)) { var highlighter = new PanGu.HighLight.Highlighter(simpleHtmlFormatter, new PanGu.Segment()) { FragmentSize = 50 }; T_ProductName = highlighter.GetBestFragment(key.Trim(), pdProductIndex.ProductName); if (!string.IsNullOrWhiteSpace(T_ProductName)) { pdProductIndex.ProductName = T_ProductName; } } pdProductIndex.RankPrice = GetProductRankPrice(pdProductIndex.Prices, pdProductIndex.BasicPrice, priceSource, priceSourceSysNo); returnValue.Add(pdProductIndex); } catch (Exception ex) { BLL.Log.SysLog.Instance.Error(LogStatus.系统日志来源.后台, ex.Message, ex); } finally { recordIndex++; } } } catch (Exception ex) { BLL.Log.SysLog.Instance.Error(LogStatus.系统日志来源.后台, ex.Message, ex); } finally { // indexSearch.Close(); } return(returnValue); }
/// <summary> /// Add a sort specification for the <see cref="P:BrowseResult.Hits"/>. /// </summary> /// <param name="sortSpec">sort specification</param> public virtual void AddSortField(SortField sortSpec) { m_sortSpecs.Add(sortSpec); }
public SortingParam(SortField field, SortOrder order) { Field = field; Order = order; }
/// <summary> /// Append a sort field and sort order to the uri /// </summary> /// <param name="sortField">the sort field</param> /// <param name="sortOrder">the sort order</param> /// <returns>the uri builder</returns> public UriBuilder Sort(SortField sortField, SortOrder sortOrder) { this.Param("sort_on", sortField.ToStringLower()); return this.Param("sort_order", sortOrder.ToStringLower()); }
public JsonResult Index(int sortField, string sortType) { List <SupportModel> models = (from mp in _session.Query <MP_CustomerMarketPlace>() where mp.UpdateError != null && mp.UpdateError != "" select new SupportModel { Umi = mp.Id, Type = mp.Marketplace.Name, CustomerId = mp.Customer.Id, ErrorMessage = mp.UpdateError, Name = mp.DisplayName, UpdateStartDate = mp.UpdatingStart, Status = mp.GetUpdatingStatus(null) }).ToList(); SortField sortFieldEnum = sortField == 0 ? SortField.UpdateStartDate : (SortField)sortField; switch (sortFieldEnum) { case SortField.Umi: models = sortType == "asc" ? models.OrderBy(x => x.Umi).ToList() : models.OrderByDescending(x => x.Umi).ToList(); break; case SortField.MpType: models = sortType == "asc" ? models.OrderBy(x => x.Type).ToList() : models.OrderByDescending(x => x.Type).ToList(); break; case SortField.MpName: models = sortType == "asc" ? models.OrderBy(x => x.Name).ToList() : models.OrderByDescending(x => x.Name).ToList(); break; case SortField.ErrorMessage: models = sortType == "asc" ? models.OrderBy(x => x.ErrorMessage).ToList() : models.OrderByDescending(x => x.ErrorMessage).ToList(); break; case SortField.CustomerId: models = sortType == "asc" ? models.OrderBy(x => x.CustomerId).ToList() : models.OrderByDescending(x => x.CustomerId).ToList(); break; case SortField.Status: models = sortType == "asc" ? models.OrderBy(x => x.Status).ToList() : models.OrderByDescending(x => x.Status).ToList(); break; //case SortField.UpdateStartDate: default: models = sortType == "asc" ? models.OrderBy(x => x.UpdateStartDate).ToList() : models.OrderByDescending(x => x.UpdateStartDate).ToList(); break; } return(Json(new { models }, JsonRequestBehavior.AllowGet)); }
/// <summary> /// 分页获取商品信息数据 /// </summary> /// <param name="queryString"></param> /// <param name="pageIndex">第一页为1</param> /// <param name="pageSize"></param> /// <param name="totalCount"></param> /// <returns></returns> public List <Commodity> QueryIndexPage(string queryString, int pageIndex, int pageSize, out int totalCount, string priceFilter, string priceOrderBy) { totalCount = 0; IndexSearcher searcher = null; try { List <Commodity> ciList = new List <Commodity>(); FSDirectory dir = FSDirectory.Open(StaticConstant.IndexPath); searcher = new IndexSearcher(dir); Analyzer analyzer = new PanGuAnalyzer(); //--------------------------------------这里配置搜索条件 QueryParser parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, "title", analyzer); Query query = parser.Parse(queryString); pageIndex = Math.Max(1, pageIndex);//索引从1开始 int startIndex = (pageIndex - 1) * pageSize; int endIndex = pageIndex * pageSize; NumericRangeFilter <float> numPriceFilter = null; if (!string.IsNullOrWhiteSpace(priceFilter)) { bool isContainStart = priceFilter.StartsWith("["); bool isContainEnd = priceFilter.EndsWith("]"); string[] floatArray = priceFilter.Replace("[", "").Replace("]", "").Replace("{", "").Replace("}", "").Split(','); float start = 0; float end = 0; if (!float.TryParse(floatArray[0], out start) || !float.TryParse(floatArray[1], out end)) { throw new Exception("Wrong priceFilter"); } numPriceFilter = NumericRangeFilter.NewFloatRange("price", start, end, isContainStart, isContainEnd); } Sort sort = new Sort(); if (!string.IsNullOrWhiteSpace(priceOrderBy)) { SortField sortField = new SortField("price", SortField.FLOAT, priceOrderBy.EndsWith("asc", StringComparison.CurrentCultureIgnoreCase)); sort.SetSort(sortField); } TopDocs docs = searcher.Search(query, numPriceFilter, 10000, sort); //TopDocs docs = searcher.Search(query, null, 10000); totalCount = docs.TotalHits; //PrintScores(docs, startIndex, endIndex, searcher); for (int i = startIndex; i < endIndex && i < totalCount; i++) { Document doc = searcher.Doc(docs.ScoreDocs[i].Doc); ciList.Add(DocumentToCommodityInfo(doc)); } return(ciList); } finally { if (searcher != null) { searcher.Dispose(); } } }
private string GetSortField(SortField sortField) { string val = string.Empty; switch (sortField) { case SortField.StartTime: val = "start_time"; break; case SortField.Type: val = "type"; break; case SortField.QueueAccountId: val = "queue_account_id"; break; case SortField.CallerIdNumber: val = "caller_id_number"; break; case SortField.WaitTime: val = "wait_time"; break; case SortField.TalkTime: val = "talk_time"; break; case SortField.MemberAccountId: val = "member_account_id"; break; case SortField.EnterPosition: val = "enter_position"; break; case SortField.ExitPosition: val = "exit_position"; break; case SortField.AbandonPosition: val = "abandon_position"; break; default: throw new NotImplementedException("No handler for the value " + sortField.ToString() + " has been implemented."); } return val; }
/// <summary> /// Search for listings by keyword. /// </summary> /// <param name="searchTerms">Specify keywords to search on, separated by spaces or semicolons. You can also use the operators AND and NOT to control keyword matching.</param> /// <param name="sortOn">Specify the field to sort on</param> /// <param name="sortOrder">Specify the direction to sort on </param> /// <param name="minPrice">Minimum for restricting price ranges. Values are in US dollars and may include cents.</param> /// <param name="maxPrice">Maximum for restricting price ranges. Values are in US dollars and may include cents.</param> /// <param name="searchDescription">If true, listing descriptions will count towards search matches. (This may produce less relevant results.)</param> /// <param name="offset">To page through large result sets</param> /// <param name="limit">Specify the number of results to return</param> /// <param name="detailLevel">control how much information to return</param> /// <returns>the async state of the request</returns> public IAsyncResult GetListingsByKeyword(IEnumerable<string> searchTerms, SortField sortOn, SortOrder sortOrder, decimal? minPrice, decimal? maxPrice, bool searchDescription, int offset, int limit, DetailLevel detailLevel) { if (!ServiceHelper.TestCallPrerequisites(this, this.GetListingsByKeywordCompleted, this.etsyContext)) { return null; } // error if the given min price is more than the given max price if (minPrice.HasValue && maxPrice.HasValue && (minPrice.Value > maxPrice.Value)) { var errorResult = new ResultEventArgs<Listings>(null, new ResultStatus("Invalid price range", null)); ServiceHelper.TestSendEvent(this.GetListingsByKeywordCompleted, this, errorResult); return null; } UriBuilder uriBuilder = UriBuilder.Start(this.etsyContext, "listings/keywords/") .Append(searchTerms) .Sort(sortOn, sortOrder) .OptionalParam("min_price", minPrice) .OptionalParam("max_price", maxPrice) .Param("search_description", searchDescription) .OffsetLimit(offset, limit) .DetailLevel(detailLevel); return ServiceHelper.GenerateRequest(this, uriBuilder.Result(), this.GetListingsByKeywordCompleted); }
/// <summary> /// Initializes a new instance of the <see cref="T:Switchvox.CallQueueLogs.Search"/> class to be executed against a single call queue /// </summary> /// <param name="startDate">The minimum date to search from.</param> /// <param name="endDate">The maximum date to search to.</param> /// <param name="queueAccountId">The Call Queue Account ID to retrieve data for.</param> /// <param name="callTypes">A combination of flags indicating the type of calls to include in the search results.</param> /// <param name="ignoreWeekends">Whether weekends should be excluded from the search results.</param> /// <param name="itemsPerPage">The number of results to return in this request. Additional items can be retrieved by making additional requests and incrementing the pageNumber parameter</param> /// <param name="pageNumber">The page of results to return in this request. Used in conjunction with the itemsPerPage parameter.</param> /// <param name="sortOrder">How the search results will be sorted.</param> /// <param name="sortField">The field of the search results to sort on</param> public Search(DateTime startDate, DateTime endDate, string queueAccountId, CallTypes callTypes, bool ignoreWeekends = false, int itemsPerPage = 50, int pageNumber = 1, SortOrder sortOrder = SortOrder.Asc, SortField sortField = SortField.StartTime) : this(startDate, endDate, new[] { queueAccountId }, callTypes, ignoreWeekends, itemsPerPage, pageNumber, sortOrder, sortField) { }
/// <summary>Adds a <see cref="SortField"/> to the bindings.</summary> /// <remarks> /// Adds a <see cref="SortField"/> to the bindings. /// <para/> /// This can be used to reference a DocValuesField, a field from /// FieldCache, the document's score, etc. /// </remarks> public void Add(SortField sortField) { map[sortField.Field] = sortField; }
public IList<WebChannelGroup> GetRadioGroups(SortField? sort = SortField.User, SortOrder? order = SortOrder.Asc) { return RadioChannelGroup.ListAll().Select(chg => chg.ToWebChannelGroup()).SortGroupList(sort, order).ToList(); }
/// <summary> /// Get all the listings in a shop. /// </summary> /// <param name="userId">the user id</param> /// <param name="sortOn">field to sort on</param> /// <param name="sortOrder">sort ascending or descending</param> /// <param name="sectionId">shop section to show</param> /// <param name="offset">the search results offset</param> /// <param name="limit">the search limit</param> /// <param name="detailLevel">the level of detail</param> /// <returns>the async state</returns> public IAsyncResult GetShopListings(int userId, SortField sortOn, SortOrder sortOrder, int? sectionId, int offset, int limit, DetailLevel detailLevel) { if (!ServiceHelper.TestCallPrerequisites(this, this.GetShopListingsCompleted, this.etsyContext)) { return null; } UriBuilder uriBuilder = UriBuilder.Start(this.etsyContext, "shops", userId) .Append("/listings") .Sort(sortOn, sortOrder) .OptionalParam("section_id", sectionId) .OffsetLimit(offset, limit) .DetailLevel(detailLevel); return ServiceHelper.GenerateRequest(this, uriBuilder.Result(), this.GetShopListingsCompleted); }
public IList<WebChannelDetailed> GetRadioChannelsDetailedByRange(int groupId, int start, int end, SortField? sort = SortField.User, SortOrder? order = SortOrder.Asc) { return _tvBusiness.GetRadioGuideChannelsForGroup(groupId).Select(ch => ch.ToWebChannelDetailed()).SortChannelList(sort, order).TakeRange(start, end).ToList(); }
protected static extern void Sort(IntPtr pItem, SortField eField, SortOrder eOrder, [MarshalAs(UnmanagedType.U1)]bool bRecurse);
protected bool IsSortByPoint(UserPointType type) { return(SortField.ToString() == type.ToString()); }
/// <summary> /// Creates one of these objects. </summary> /// <param name="totalHits"> Total number of hits for the query. </param> /// <param name="scoreDocs"> The top hits for the query. </param> /// <param name="fields"> The sort criteria used to find the top hits. </param> /// <param name="maxScore"> The maximum score encountered. </param> public TopFieldDocs(int totalHits, ScoreDoc[] scoreDocs, SortField[] fields, float maxScore) : base(totalHits, scoreDocs, maxScore) { this.Fields = fields; }
public IList<WebChannelGroup> GetRadioGroupsByRange(int start, int end, SortField? sort = SortField.User, SortOrder? order = SortOrder.Asc) { return RadioChannelGroup.ListAll().Select(chg => chg.ToWebChannelGroup()).SortGroupList(sort, order).TakeRange(start, end).ToList(); }
/// <summary> /// Get all the listings in a shop. /// </summary> /// <param name="userName">the user name</param> /// <param name="sortOn">field to sort on</param> /// <param name="sortOrder">sort ascending or descending</param> /// <param name="sectionId">shop section to show</param> /// <param name="offset">the search results offset</param> /// <param name="limit">the search limit</param> /// <param name="detailLevel">the level of detail</param> /// <returns>the async state</returns> public IAsyncResult GetShopListings(string userName, SortField sortOn, SortOrder sortOrder, int? sectionId, int offset, int limit, DetailLevel detailLevel) { if (!RequestHelper.TestCallPrerequisites(this, this.GetShopListingsCompleted, this.etsyContext)) { return null; } EtsyUriBuilder etsyUriBuilder = EtsyUriBuilder.Start(this.etsyContext, "shops", userName) .Append("/listings") .Sort(sortOn, sortOrder) .OptionalParam("section_id", sectionId) .OffsetLimit(offset, limit) .DetailLevel(detailLevel); return this.dataRetriever.StartRetrieve(etsyUriBuilder.Result(), this.GetShopListingsCompleted); }
private void AssertSortFieldEquals(SortField sortField, string expectedFieldName, OrderingDirection expectedDirection, int expectedType) { Assert.That(sortField.Field, Is.EqualTo(expectedFieldName)); Assert.That(sortField.Type, Is.EqualTo(expectedType), "SortField type for field " + expectedFieldName); Assert.That(sortField.Reverse, Is.EqualTo(expectedDirection == OrderingDirection.Desc), "Reverse"); }