示例#1
0
        /// <summary>
        /// 重建索引
        /// </summary>
        public void RebuildIndex()
        {
            //pageSize参数决定了每次批量取多少条数据进行索引。要注意的是,如果是分布式搜索,客户端会将这部分数据通过WCF传递给服务器端,而WCF默认的最大传输数据量是65535B,pageSize较大时这个设置显然是不够用的,WCF会报400错误;系统现在将最大传输量放宽了,但仍要注意一次不要传输过多,如遇异常,可适当调小pageSize的值
            int  pageSize     = 1000;
            int  pageIndex    = 1;
            long totalRecords = 0;
            bool isBeginning  = true;
            bool isEndding    = false;

            do
            {
                //分页获取专题列表
                PagingDataSet <TopicEntity> groups = topicService.GetsForAdmin(null, null, null, null, null, null, null, null, pageSize, pageIndex);
                totalRecords = groups.TotalRecords;

                isEndding = (pageSize * pageIndex < totalRecords) ? false : true;

                //重建索引
                List <TopicEntity> groupList = groups.ToList <TopicEntity>();

                IEnumerable <Document> docs = TopicIndexDocument.Convert(groupList);

                searchEngine.RebuildIndex(docs, isBeginning, isEndding);

                isBeginning = false;
                pageIndex++;
            }while (!isEndding);
        }
示例#2
0
        /// <summary>
        /// 重建索引
        /// </summary>
        public void RebuildIndex()
        {   //pageSize参数决定了每次批量取多少条数据进行索引。要注意的是,如果是分布式搜索,客户端会将这部分数据通过WCF传递给服务器端,而WCF默认的最大传输数据量是65535B,pageSize较大时这个设置显然是不够用的,WCF会报400错误;系统现在将最大传输量放宽了,但仍要注意一次不要传输过多,如遇异常,可适当调小pageSize的值
            int            pageSize     = 1000;
            int            pageIndex    = 1;
            long           totalRecords = 0;
            bool           isBeginning  = true;
            bool           isEndding    = false;
            MicroblogQuery query        = new MicroblogQuery();

            do
            {
                //分页获取微博列表
                PagingDataSet <MicroblogEntity> microblogs = microBlogService.GetMicroblogs(query, pageSize, pageIndex);
                totalRecords = microblogs.TotalRecords;

                isEndding = (pageSize * pageIndex < totalRecords) ? false : true;

                //重建索引
                List <MicroblogEntity> microblogsList = microblogs.ToList <MicroblogEntity>();

                IEnumerable <Document> docs = MicroblogIndexDocument.Convert(microblogsList);

                searchEngine.RebuildIndex(docs, isBeginning, isEndding);

                isBeginning = false;
                pageIndex++;
            }while (!isEndding);
        }
        /// <summary>
        /// 重建索引
        /// </summary>
        public void RebuildIndex()
        {
            //pageSize参数决定了每次批量取多少条数据进行索引。要注意的是,如果是分布式搜索,
            //客户端会将这部分数据通过WCF传递给服务器端,而WCF默认的最大传输数据量是65535B,
            //pageSize较大时这个设置显然是不够用的,WCF会报400错误;系统现在将最大传输量放宽了,
            //但仍要注意一次不要传输过多,如遇异常,可适当调小pageSize的值
            int  pageSize     = 1000;
            int  pageIndex    = 1;
            long totalRecords = 0;
            bool isBeginning  = true;
            bool isEndding    = false;

            do
            {
                //分页获取帖子列表
                PagingDataSet <Journal> journals = journalService.Gets(pageIndex, pageSize, "id");
                totalRecords = journals.TotalRecords;

                isEndding = (pageSize * pageIndex < totalRecords) ? false : true;

                //重建索引
                List <Journal> journalList = journals.ToList <Journal>();

                IEnumerable <Document> docs = JournalIndexDocument.Convert(journalList);

                searchEngine.RebuildIndex(docs, isBeginning, isEndding);

                isBeginning = false;
                pageIndex++;
            }while (!isEndding);
        }
示例#4
0
        /// <summary>
        /// 资讯分页搜索
        /// </summary>
        /// <param name="cmsQuery">搜索条件</param>
        /// <returns>符合搜索条件的分页集合</returns>
        public PagingDataSet <ContentItem> Search(CmsFullTextQuery cmsQuery)
        {
            if (cmsQuery.ContentFolderId == 0)
            {
                if (string.IsNullOrWhiteSpace(cmsQuery.Keyword))
                {
                    return(new PagingDataSet <ContentItem>(new List <ContentItem>()));
                }
            }

            LuceneSearchBuilder searchBuilder = BuildLuceneSearchBuilder(cmsQuery);

            //使用LuceneSearchBuilder构建Lucene需要Query、Filter、Sort
            Query  query  = null;
            Filter filter = null;
            Sort   sort   = null;

            searchBuilder.BuildQuery(out query, out filter, out sort);

            //调用SearchService.Search(),执行搜索
            PagingDataSet <Document> searchResult = searchEngine.Search(query, filter, sort, cmsQuery.PageIndex, cmsQuery.PageSize);
            IEnumerable <Document>   docs         = searchResult.ToList <Document>();

            //解析出搜索结果中的资讯ID
            List <long> cmsContentItemIds = new List <long>();
            //获取索引中资讯的标签
            Dictionary <long, IEnumerable <string> > cmsTags = new Dictionary <long, IEnumerable <string> >();

            foreach (Document doc in docs)
            {
                long cmsContentItemId = long.Parse(doc.Get(CmsIndexDocument.ContentItemId));
                cmsContentItemIds.Add(cmsContentItemId);
                cmsTags[cmsContentItemId] = doc.GetValues(CmsIndexDocument.Tag).ToList <string>();
            }

            //根据资讯ID列表批量查询资讯实例
            IEnumerable <ContentItem> contentItemList = contentItemService.GetContentItems(cmsContentItemIds);

            foreach (var contentItem in contentItemList)
            {
                if (cmsTags.ContainsKey(contentItem.ContentItemId))
                {
                    contentItem.TagNames = cmsTags[contentItem.ContentItemId];
                }
            }

            //组装分页对象
            PagingDataSet <ContentItem> contentItems = new PagingDataSet <ContentItem>(contentItemList)
            {
                TotalRecords  = searchResult.TotalRecords,
                PageSize      = searchResult.PageSize,
                PageIndex     = searchResult.PageIndex,
                QueryDuration = searchResult.QueryDuration
            };

            return(contentItems);
        }
示例#5
0
        /// <summary>
        /// 日志分页搜索
        /// </summary>
        /// <param name="WikiQuery">搜索条件</param>
        /// <returns>符合搜索条件的分页集合</returns>
        public PagingDataSet <WikiPage> Search(WikiFullTextQuery WikiQuery)
        {
            if (WikiQuery.SiteCategoryId == 0)
            {
                if (string.IsNullOrWhiteSpace(WikiQuery.Keyword))
                {
                    return(new PagingDataSet <WikiPage>(new List <WikiPage>()));
                }
            }

            LuceneSearchBuilder searchBuilder = BuildLuceneSearchBuilder(WikiQuery);

            //使用LuceneSearchBuilder构建Lucene需要Query、Filter、Sort
            Query  query  = null;
            Filter filter = null;
            Sort   sort   = null;

            searchBuilder.BuildQuery(out query, out filter, out sort);

            //调用SearchService.Search(),执行搜索
            PagingDataSet <Document> searchResult = searchEngine.Search(query, filter, sort, WikiQuery.PageIndex, WikiQuery.PageSize);
            IEnumerable <Document>   docs         = searchResult.ToList <Document>();

            //解析出搜索结果中的日志ID
            List <long> WikiPageIds = new List <long>();
            //获取索引中百科的标签
            Dictionary <long, IEnumerable <string> > WikiTags = new Dictionary <long, IEnumerable <string> >();

            foreach (Document doc in docs)
            {
                long WikiPageId = long.Parse(doc.Get(WikiIndexDocument.PageId));
                WikiPageIds.Add(WikiPageId);
                WikiTags[WikiPageId] = doc.GetValues(WikiIndexDocument.Tag).ToList <string>();
            }

            //根据日志ID列表批量查询日志实例
            IEnumerable <WikiPage> WikiPageList = wikiService.GetWikiPages(WikiPageIds);

            foreach (var WikiPage in WikiPageList)
            {
                if (WikiTags.ContainsKey(WikiPage.PageId))
                {
                    WikiPage.TagNames = WikiTags[WikiPage.PageId];
                }
            }

            //组装分页对象
            PagingDataSet <WikiPage> WikiPages = new PagingDataSet <WikiPage>(WikiPageList)
            {
                TotalRecords  = searchResult.TotalRecords,
                PageSize      = searchResult.PageSize,
                PageIndex     = searchResult.PageIndex,
                QueryDuration = searchResult.QueryDuration
            };

            return(WikiPages);
        }
示例#6
0
        /// <summary>
        /// 微博分页搜索
        /// </summary>
        /// <param name="query">搜索条件</param>
        /// <returns>符合搜索条件的分页集合</returns>
        public PagingDataSet <MicroblogEntity> Search(MicroblogFullTextQuery microBlogQuery)
        {
            if (microBlogQuery.Keywords == null && string.IsNullOrWhiteSpace(microBlogQuery.Keyword) && microBlogQuery.SearchTerm == MicroblogSearchTerm.ALL)
            {
                return(new PagingDataSet <MicroblogEntity>(new List <MicroblogEntity>()));
            }

            LuceneSearchBuilder searchBuilder = BuildLuceneSearchBuilder(microBlogQuery);

            //使用LuceneSearchBuilder构建Lucene需要Query、Filter、Sort
            Query  query  = null;
            Filter filter = null;
            Sort   sort   = null;

            searchBuilder.BuildQuery(out query, out filter, out sort);

            //调用SearchService.Search(),执行搜索
            PagingDataSet <Document> searchResult = searchEngine.Search(query, filter, sort, microBlogQuery.PageIndex, microBlogQuery.PageSize);
            IEnumerable <Document>   docs         = searchResult.ToList <Document>();

            //解析出搜索结果中的微博ID
            List <long> microblogIds = new List <long>();

            foreach (Document doc in docs)
            {
                long microblogId = long.Parse(doc.Get(MicroblogIndexDocument.MicroblogId));
                microblogIds.Add(microblogId);
            }

            //根据微博ID列表批量查询微博实例
            IEnumerable <MicroblogEntity> microblogList = microBlogService.GetMicroblogs(microblogIds);

            //组装分页对象
            PagingDataSet <MicroblogEntity> microblogs = new PagingDataSet <MicroblogEntity>(microblogList)
            {
                TotalRecords  = searchResult.TotalRecords,
                PageSize      = searchResult.PageSize,
                PageIndex     = searchResult.PageIndex,
                QueryDuration = searchResult.QueryDuration
            };

            return(microblogs);
        }
示例#7
0
        /// <summary>
        /// 关注的日志
        /// </summary>
        public ActionResult Subscribed(string spaceKey, int pageIndex = 1)
        {
            PagingDataSet<BlogThread> blogs = new PagingDataSet<BlogThread>(new List<BlogThread>());
            pageResourceManager.InsertTitlePart("我的关注");
            PagingDataSet<long> threadIds = subscribeService.GetPagingObjectIds(UserContext.CurrentUser.UserId, pageIndex);
            if (threadIds != null && threadIds.Count > 0)
            {
                IEnumerable<BlogThread> blogList = blogService.GetBlogThreads(threadIds.ToList());
                blogs = new PagingDataSet<BlogThread>(blogList)
                {
                    TotalRecords = threadIds.TotalRecords,
                    PageSize = threadIds.PageSize,
                    PageIndex = threadIds.PageIndex,
                    QueryDuration = threadIds.QueryDuration
                };
            }

            return View(blogs);
        }
示例#8
0
        /// <summary>
        /// 用户搜索
        /// </summary>
        /// <param name="userQuery">搜索条件</param>
        /// <returns>符合搜索条件的User分页集合</returns>
        public PagingDataSet <User> Search(UserFullTextQuery userQuery)
        {
            LuceneSearchBuilder searchBuilder = BuildLuceneSearchBuilder(userQuery);

            //使用LuceneSearchBuilder构建Lucene需要Query、Filter、Sort
            Query  query  = null;
            Filter filter = null;
            Sort   sort   = null;

            searchBuilder.BuildQuery(out query, out filter, out sort);

            //调用SearchEngine.Search(),执行搜索
            PagingDataSet <Document> searchResult = searchEngine.Search(query, filter, sort, userQuery.PageIndex, userQuery.PageSize);
            IEnumerable <Document>   docs         = searchResult.ToList <Document>();

            //解析出搜索结果中的用户ID
            List <long> userIds = new List <long>();

            foreach (Document doc in docs)
            {
                long userId = long.Parse(doc.Get(UserIndexDocument.UserId));
                userIds.Add(userId);
            }

            //根据用户ID列表批量查询用户实例
            IEnumerable <User> userList = userService.GetFullUsers(userIds);

            //根据用户ID列表批量查询UserProfile实例,利用Repository的自动缓存机制,减少页面加载时的关联数据库查询次数
            //对于UserProfile的Tag、WorkExperience、EducationExperience,目前页面列表不显示,暂不处理
            userProfileService.GetUserProfiles(userIds);

            //组装分页对象
            PagingDataSet <User> users = new PagingDataSet <User>(userList)
            {
                TotalRecords  = searchResult.TotalRecords,
                PageSize      = searchResult.PageSize,
                PageIndex     = searchResult.PageIndex,
                QueryDuration = searchResult.QueryDuration
            };

            return(users);
        }
示例#9
0
        /// <summary>
        /// 问答分页搜索
        /// </summary>
        /// <param name="askQuery">搜索条件</param>
        /// <returns>符合条件的分页集合</returns>
        public PagingDataSet <AskQuestion> Search(AskFullTextQuery askQuery)
        {
            if (string.IsNullOrWhiteSpace(askQuery.Keyword) && askQuery.IsRelation == false && askQuery.IsAlike == false)
            {
                return(new PagingDataSet <AskQuestion>(new List <AskQuestion>()));
            }
            LuceneSearchBuilder searchBuilder = BuilderLuceneSearchBuilder(askQuery);

            Query  query  = null;
            Filter filter = null;
            Sort   sort   = null;

            searchBuilder.BuildQuery(out query, out filter, out sort);

            //调用SearchService.Search(),执行搜索
            PagingDataSet <Document> searchResult = searchEngine.Search(query, filter, sort, askQuery.PageIndex, askQuery.PageSize);
            IEnumerable <Document>   docs         = searchResult.ToList <Document>();

            //问题ids
            List <long> questionIds = new List <long>();

            foreach (Document doc in docs)
            {
                long questionId = long.Parse(doc.Get(AskIndexDocument.QuestionId));
                questionIds.Add(questionId);
            }

            //根据ids批量获取问题实体
            IEnumerable <AskQuestion> questionList = askService.GetQuestions(questionIds);

            //组装分页对象
            PagingDataSet <AskQuestion> questions = new PagingDataSet <AskQuestion>(questionList)
            {
                TotalRecords  = searchResult.TotalRecords,
                PageIndex     = searchResult.PageIndex,
                PageSize      = searchResult.PageSize,
                QueryDuration = searchResult.QueryDuration
            };

            return(questions);
        }
示例#10
0
        /// <summary>
        /// 照片详细显示
        /// </summary>
        /// <returns></returns>
        public ActionResult Detail(long photoId)
        {
            Photo photo = photoService.GetPhoto(photoId);

            //更新计数
            CountService countService = new CountService(TenantTypeIds.Instance().Photo());

            countService.ChangeCount(CountTypes.Instance().HitTimes(), photoId, photo.UserId, 1, true);

            Album album = photo.Album;

            if (photo == null || !authorizer.Album_View(album))
            {
                if (Request.IsAjaxRequest())
                {
                    return(Json(new StatusMessageData(StatusMessageType.Hint, "没有浏览照片的权限")));
                }
                else
                {
                    return(Redirect(SiteUrls.Instance().SystemMessage(TempData, new SystemMessageViewModel
                    {
                        Body = "没有浏览照片的权限",
                        Title = "没有权限",
                        StatusMessageType = StatusMessageType.Hint
                    })));
                }
            }

            IUser currentUser            = UserContext.CurrentUser;
            PagingDataSet <Photo> photos = photoService.GetPhotosOfAlbum(null, photo.AlbumId,
                                                                         currentUser != null && currentUser.UserId == album.UserId, pageSize: 1000, pageIndex: 1);

            ViewData["album"]  = album;
            ViewData["photos"] = photos.ToList();
            if (Request.IsAjaxRequest())
            {
                return(PartialView("_Details", photo));
            }
            return(View(photo));
        }
示例#11
0
        /// <summary>
        /// 重建索引
        /// </summary>
        public void RebuildIndex()
        {
            int  pageSize     = 1000;
            int  pageIndex    = 1;
            long totalRecords = 0;
            bool isBeginning  = true;
            bool isEndding    = false;

            do
            {
                PagingDataSet <Photo> photos = photoService.GetPhotosForAdmin(null, null, null, null, null, null, pageSize, pageIndex);
                totalRecords = photos.TotalRecords;
                isEndding    = (pageSize * pageIndex < totalRecords) ? false : true;

                List <Photo>           photoList = photos.ToList <Photo>();
                IEnumerable <Document> docs      = PhotoIndexDocument.Convert(photoList);
                searchEngine.RebuildIndex(docs, isBeginning, isEndding);

                isBeginning = false;
                pageIndex++;
            } while (!isEndding);
        }
示例#12
0
        /// <summary>
        /// 重建索引
        /// </summary>
        public void RebuildIndex()
        {
            int  pageSize     = 1000;
            int  pageIndex    = 1;
            long totalRecords = 0;
            bool isBeginning  = true;
            bool isEndding    = false;

            do
            {
                PagingDataSet <AskQuestion> askQuestions = askService.GetQuestionsForAdmin(null, null, null, null, null, null, null, pageSize, pageIndex);
                totalRecords = askQuestions.TotalRecords;
                isEndding    = (pageSize * pageIndex < totalRecords) ? false : true;

                //重建索引
                List <AskQuestion>     askQuestionList = askQuestions.ToList <AskQuestion>();
                IEnumerable <Document> docs            = AskIndexDocument.Convert(askQuestionList);
                searchEngine.RebuildIndex(docs, isBeginning, isEndding);
                isBeginning = false;
                pageIndex++;
            } while (!isEndding);
        }
示例#13
0
        /// <summary>
        /// 照片搜索
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagingDataSet <Photo> Search(PhotoFullTextQuery query)
        {
            LuceneSearchBuilder searchBuilder = BuildLuceneSearchBuilder(query);

            //使用LuceneSearchBuilder构建Lucene需要Query、Filter、Sort
            Query  photoQuery = null;
            Filter filter     = null;
            Sort   sort       = null;

            searchBuilder.BuildQuery(out photoQuery, out filter, out sort);

            //调用SearchEngine.Search(),执行搜索
            PagingDataSet <Document> searchResult = searchEngine.Search(photoQuery, filter, sort, query.PageIndex, query.PageSize);
            IEnumerable <Document>   docs         = searchResult.ToList <Document>();

            //解析出PhotoId,组装Photo实体
            List <long> photoIds = new List <long>();

            foreach (var doc in docs)
            {
                long photoId = long.Parse(doc.Get(PhotoIndexDocument.PhotoId));
                photoIds.Add(photoId);
            }
            IEnumerable <Photo> photoList = photoService.GetPhotos(photoIds);

            //组装分页集合
            PagingDataSet <Photo> photos = new PagingDataSet <Photo>(photoList)
            {
                TotalRecords  = searchResult.TotalRecords,
                PageIndex     = searchResult.PageIndex,
                PageSize      = searchResult.PageSize,
                QueryDuration = searchResult.QueryDuration
            };

            return(photos);
        }
示例#14
0
        /// <summary>
        /// 微博分页搜索
        /// </summary>
        /// <param name="query">搜索条件</param>
        /// <returns>符合搜索条件的分页集合</returns>
        public PagingDataSet <BarEntity> Search(BarFullTextQuery barQuery)
        {
            if (string.IsNullOrWhiteSpace(barQuery.Keyword))
            {
                return(new PagingDataSet <BarEntity>(new List <BarEntity>()));
            }

            LuceneSearchBuilder searchBuilder = BuildLuceneSearchBuilder(barQuery);

            //使用LuceneSearchBuilder构建Lucene需要Query、Filter、Sort
            Query  query  = null;
            Filter filter = null;
            Sort   sort   = null;

            searchBuilder.BuildQuery(out query, out filter, out sort);

            //调用SearchService.Search(),执行搜索
            PagingDataSet <Document> searchResult = searchEngine.Search(query, filter, sort, barQuery.PageIndex, barQuery.PageSize);
            IEnumerable <Document>   docs         = searchResult.ToList <Document>();

            //解析出搜索结果中的发帖ID
            List <long> barthreadIds = new List <long>();
            //解析出搜索结果中的回帖ID
            List <long> barpostIds = new List <long>();
            //获取索引中发帖的标签
            Dictionary <long, List <string> > barTags = new Dictionary <long, List <string> >();
            //获取帖吧名
            Dictionary <long, string> barSectionNames = new Dictionary <long, string>();
            //获取索引中回帖的标题
            Dictionary <long, string> barPostSubjects = new Dictionary <long, string>();

            foreach (Document doc in docs)
            {
                //是回帖
                if (doc.Get(BarIndexDocument.IsPost) == "1")
                {
                    long postId = long.Parse(doc.Get(BarIndexDocument.PostId));
                    barpostIds.Add(postId);
                    string subject = doc.Get(BarIndexDocument.Subject);
                    barPostSubjects[postId] = subject;
                }
                else
                {
                    long threadId = long.Parse(doc.Get(BarIndexDocument.ThreadId));
                    barthreadIds.Add(threadId);
                    //if (!string.IsNullOrWhiteSpace(doc.Get(BarIndexDocument.Tag)))
                    //{
                    barTags[threadId] = doc.GetValues(BarIndexDocument.Tag).ToList <string>();
                    //}
                }
                long sectionId = long.Parse(doc.Get(BarIndexDocument.SectionId));
                if (!barSectionNames.ContainsKey(sectionId))
                {
                    string sectionName = barSectionService.Get(sectionId).Name;
                    barSectionNames[sectionId] = sectionName;
                }
            }

            //根据发帖ID列表批量查询发帖实例
            IEnumerable <BarThread> barThreadList = barThreadService.GetBarThreads(barthreadIds);
            //根据回帖ID列表批量查询回帖实例
            IEnumerable <BarPost> barPostList = barPostService.GetBarPosts(barpostIds);



            //组装帖子列表
            List <BarEntity> barEntityList = new List <BarEntity>();

            foreach (var barThread in barThreadList)
            {
                BarEntity barEntity = new BarEntity();
                barEntity.SectionId = barThread.SectionId;
                barEntity.ThreadId  = barThread.ThreadId;
                barEntity.PostId    = 0;
                barEntity.Subject   = barThread.Subject;
                barEntity.Body      = barThread.GetBody();
                barEntity.UserId    = barThread.UserId;
                barEntity.Author    = barThread.Author;
                if (barTags.Keys.Contains(barEntity.ThreadId))
                {
                    barEntity.Tag = barTags.Count == 0 ? new List <string>() : barTags[barEntity.ThreadId];
                }
                else
                {
                    barEntity.Tag = new List <string>();
                }
                if (barSectionNames.Keys.Contains(barEntity.SectionId))
                {
                    barEntity.SectionName = barSectionNames.Count == 0 ? "" : barSectionNames[barEntity.SectionId];
                }
                else
                {
                    barEntity.SectionName = "";
                }
                barEntity.DateCreated = barThread.DateCreated;
                barEntity.IsPost      = false;
                barEntityList.Add(barEntity);
            }
            foreach (var barPost in barPostList)
            {
                BarEntity barEntity = new BarEntity();
                barEntity.SectionId = barPost.SectionId;
                barEntity.ThreadId  = barPost.ThreadId;
                barEntity.PostId    = barPost.PostId;
                barEntity.Subject   = barPostSubjects[barPost.PostId];
                barEntity.UserId    = barPost.UserId;
                barEntity.Body      = barPost.GetBody();
                barEntity.Author    = barPost.Author;
                barEntity.Tag       = null;
                if (barSectionNames.Keys.Contains(barEntity.SectionId))
                {
                    barEntity.SectionName = barSectionNames.Count == 0 ? "" : barSectionNames[barEntity.SectionId];
                }
                else
                {
                    barEntity.SectionName = "";
                }
                barEntity.DateCreated = barPost.DateCreated;
                barEntity.IsPost      = true;
                barEntityList.Add(barEntity);
            }

            //组装分页对象
            PagingDataSet <BarEntity> barEntities = new PagingDataSet <BarEntity>(barEntityList.OrderByDescending(b => b.DateCreated))
            {
                TotalRecords  = searchResult.TotalRecords,
                PageSize      = searchResult.PageSize,
                PageIndex     = searchResult.PageIndex,
                QueryDuration = searchResult.QueryDuration
            };

            return(barEntities);
        }
示例#15
0
        /// <summary>
        /// 搜索共同关注的人
        /// </summary>
        /// <param name="userId">粉丝的用户ID</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">分页大小</param>
        /// <param name="followedUserIdDic">每个相同关注用户中共同关注的用户ID列表</param>
        /// <param name="followedUserDic">每个共同关注的用户的ID与User的映射</param>
        /// <returns>符合搜索条件的User分页集合</returns>
        public PagingDataSet <User> SearchInterestedWithFollows(long userId, int pageIndex, int pageSize, out Dictionary <long, IEnumerable <long> > followedUserIdDic, out Dictionary <long, User> followedUserDic)
        {
            followedUserIdDic = new Dictionary <long, IEnumerable <long> >();
            followedUserDic   = new Dictionary <long, User>();

            if (userId <= 0)
            {
                return(new PagingDataSet <User>(new List <User>()));
            }

            //先查询当前用户关注的人(包括“悄悄关注”的用户),此处需要调用数据库查询,因为索引中没有存储“是否悄悄关注”属性
            IEnumerable <long> myFollowedUserIds = followService.GetPortionFollowedUserIds(userId);

            if (myFollowedUserIds != null && myFollowedUserIds.Count() == 0)
            {
                return(new PagingDataSet <User>(new List <User>()));
            }

            //黑名单用户
            IEnumerable <long> stopUserIds = new PrivacyService().GetStopedUsers(userId).Select(n => n.Key);

            //搜索“我”关注的人中包含“共同关注的人”的用户
            //使用LuceneSearchBuilder构建Lucene需要Query、Filter、Sort
            Query  query  = null;
            Filter filter = null;
            Sort   sort   = null;
            LuceneSearchBuilder searchBuilder = new LuceneSearchBuilder();

            searchBuilder.WithFields(FollowedUserIds, myFollowedUserIds.Select(n => n.ToString()), true)
            .NotWithField(UserId, userId.ToString())                                         //排除掉当前用户
            .NotWithFields(UserId, myFollowedUserIds.Select(n => n.ToString()))              //排除掉已关注用户
            .NotWithFields(UserIndexDocument.UserId, stopUserIds.Select(n => n.ToString())); //排除掉黑名单用户
            searchBuilder.BuildQuery(out query, out filter, out sort);

            PagingDataSet <Document> searchResult = searchEngine.Search(query, filter, sort, pageIndex, pageSize);
            IEnumerable <Document>   docs         = searchResult.ToList <Document>();

            if (docs == null || docs.Count() == 0)
            {
                return(new PagingDataSet <User>(new List <User>()));
            }

            List <long> sameFollowedUserIdList = new List <long>();

            //解析出搜索结果中的用户ID
            List <long> followerUserIds = new List <long>();

            foreach (Document doc in docs)
            {
                long followerUserId = long.Parse(doc.Get(UserId));
                followerUserIds.Add(followerUserId);

                //“我”关注的人关注的人
                string[] followedUserIds = doc.GetValues(FollowedUserIds);

                //比较获取“共同关注的人”
                IEnumerable <long> sameFollowedUserIds = myFollowedUserIds.Intersect <long>(followedUserIds.Select(n => Convert.ToInt64(n)));
                if (!followedUserIdDic.ContainsKey(followerUserId))
                {
                    followedUserIdDic.Add(followerUserId, sameFollowedUserIds);
                }

                sameFollowedUserIdList.AddRange(sameFollowedUserIds);
            }

            //批量查询“共同关注的用户”列表
            IEnumerable <User> followerUserList = userService.GetFullUsers(followerUserIds).Where(n => n.IsCanbeFollow == true && n.IsActivated == true && n.IsBanned == false);

            //组装分页对象
            PagingDataSet <User> users = new PagingDataSet <User>(followerUserList)
            {
                TotalRecords  = searchResult.TotalRecords,
                PageSize      = searchResult.PageSize,
                PageIndex     = searchResult.PageIndex,
                QueryDuration = searchResult.QueryDuration
            };

            //批量查询“共同关注的用户”关注的“共同关注用户”列表
            IEnumerable <User> sameFollowedUserList = userService.GetFullUsers(sameFollowedUserIdList.Distinct());

            followedUserDic = sameFollowedUserList.ToDictionary(n => n.UserId);

            return(users);
        }
示例#16
0
        public async Task <GoodsInfoCategoryListDto> GetCategoryByParams(GoodsInfoCategoryParam param = null)
        {
            if (param == null)
            {
                return(null);
            }

            GoodsInfoCategoryListDto dto       = new GoodsInfoCategoryListDto();
            ScreeningDto             screenDto = new ScreeningDto();

            screenDto.price_grade = new List <GradeDto>();

            List <int> ids = new List <int>();

            await Task.Run(() =>
            {
                IEnumerable <CategoryItemInBrands> inBrands = goodsCategoryService.GetCategoryItemInBrandsByCategoryItemId(param.CategoryItemid);
                foreach (var inBrandItem in inBrands)
                {
                    ids.Add(inBrandItem.BrandsId);
                }
                var brands = goodsCategoryService.GetCategoryItemBrandsIds(ids);
                ids.Clear();
                Mapper.Initialize(c => c.CreateMap <CategoryItemBrands, BrandDto>()
                                  .ForMember(dest => dest.brand_id, opt => opt.MapFrom(src => src.BrandsId))
                                  .ForMember(dest => dest.brand_name, opt => opt.MapFrom(src => src.BrandsName))
                                  );
                screenDto.brands = Mapper.Map <IEnumerable <CategoryItemBrands>, List <BrandDto> >(brands);
            });

            await Task.Run(() =>
            {
                IEnumerable <CategoryItemInChara> inCharas = goodsCategoryService.GetCategoryItemInCharaByCategoryItemId(param.CategoryItemid);
                foreach (var inCharaItem in inCharas)
                {
                    ids.Add(inCharaItem.CharaId);
                }
                var charas = goodsCategoryService.GetCategoryItemCharaIds(ids);
                ids.Clear();
                Mapper.Initialize(c => c.CreateMap <CategoryItemChara, CharaDto>()
                                  .ForMember(dest => dest.chara, opt => opt.MapFrom(src => src.CharaId))
                                  .ForMember(dest => dest.name, opt => opt.MapFrom(src => src.CharaName))
                                  );
                screenDto.characteristic = Mapper.Map <IEnumerable <CategoryItemChara>, List <CharaDto> >(charas);
            });



            await Task.Run(() =>
            {
                PagingDataSet <GoodsInfo> pageing = goodsInfoService.GetPageGoodsInfoAPI(ParamsToKeyValue(param), ParamsSortValue(param.Sort), param.PageIndex, param.PageSize);
                dto.page_total  = pageing.PageCount;
                dto.c_total     = (int)pageing.TotalRecords;
                dto.c_page_next = param.PageIndex + 1;

                var pageings = pageing.ToList();
                Mapper.Initialize(c => c.CreateMap <GoodsInfo, GoodsInfoCategoryDto>()
                                  .ForMember(dest => dest.is_vedio, opt => opt.MapFrom(src => false))
                                  .ForMember(dest => dest.goods_id, opt => opt.MapFrom(src => src.Goodsid))
                                  .ForMember(dest => dest.goods_name, opt => opt.MapFrom(src => src.GoodsName))
                                  .ForMember(dest => dest.app_price, opt => opt.MapFrom(src => src.GoodsRealPrice))
                                  .ForMember(dest => dest.comment_num, opt => opt.MapFrom(src => src.CommenCount))
                                  .ForMember(dest => dest.img_url, opt => opt.MapFrom(src => src.ImageUrl))
                                  .ForMember(dest => dest.is_free_shipping, opt => opt.MapFrom(src => true))
                                  .ForMember(dest => dest.is_new, opt => opt.MapFrom(src => false))
                                  .ForMember(dest => dest.is_promote, opt => opt.MapFrom(src => false))
                                  .ForMember(dest => dest.sold_num, opt => opt.MapFrom(src => src.BuyCount))
                                  .ForMember(dest => dest.is_hot, opt => opt.MapFrom(src => src.IsHot))
                                  );
                dto.goods_list = Mapper.Map <List <GoodsInfo>, List <GoodsInfoCategoryDto> >(pageings);
            });

            dto.screening = screenDto;
            return(dto);
        }
示例#17
0
        /// <summary>
        /// 重建索引
        /// </summary>
        public void RebuildIndex()
        {
            bool hasData = false;

            //pageSize参数决定了每次批量取多少条数据进行索引。要注意的是,如果是分布式搜索,客户端会将这部分数据通过WCF传递给服务器端,而WCF默认的最大传输数据量是65535B,pageSize较大时这个设置显然是不够用的,WCF会报400错误;系统现在将最大传输量放宽了,但仍要注意一次不要传输过多,如遇异常,可适当调小pageSize的值
            int            pageSizeBarThread     = 100;
            int            pageIndexBarThread    = 1;
            long           totalRecordsBarThread = 0;
            bool           isBeginningBarThread  = true;
            bool           isEnddingBarThread    = false;
            BarThreadQuery barThreadQuery        = new BarThreadQuery();

            do
            {
                //分页获取帖子列表
                PagingDataSet <BarThread> barThreads = barThreadService.Gets(null, barThreadQuery, pageSizeBarThread, pageIndexBarThread);
                totalRecordsBarThread = barThreads.TotalRecords;
                if (totalRecordsBarThread > 0)
                {
                    hasData = true;
                }
                isEnddingBarThread = (pageSizeBarThread * pageIndexBarThread < totalRecordsBarThread) ? false : true;

                //重建索引
                List <BarThread> barThreadList = barThreads.ToList <BarThread>();

                IEnumerable <Document> docs = BarIndexDocument.Convert(barThreadList);

                searchEngine.RebuildIndex(docs, isBeginningBarThread, false);

                isBeginningBarThread = false;
                pageIndexBarThread++;
            }while (!isEnddingBarThread);

            int          pageSizeBarPost     = 100;
            int          pageIndexBarPost    = 1;
            long         totalRecordsBarPost = 0;
            bool         isEnddingBarPost    = false;
            BarPostQuery barPostQuery        = new BarPostQuery();

            do
            {
                //分页获取帖子列表
                PagingDataSet <BarPost> barPosts = barPostService.Gets(null, barPostQuery, pageSizeBarPost, pageIndexBarPost);
                totalRecordsBarPost = barPosts.TotalRecords;
                if (totalRecordsBarPost > 0)
                {
                    hasData = true;
                }
                isEnddingBarPost = (pageSizeBarPost * pageIndexBarPost < totalRecordsBarPost) ? false : true;

                //重建索引
                List <BarPost> barPostList = barPosts.ToList <BarPost>();

                IEnumerable <Document> docs = BarIndexDocument.Convert(barPostList);

                searchEngine.RebuildIndex(docs, false, false);

                pageIndexBarPost++;
            }while (!isEnddingBarPost);

            if (hasData)
            {
                searchEngine.RebuildIndex(null, false, true);
            }
        }
示例#18
0
        //fixed by wanf
        /// <summary>
        /// 专题分页搜索
        /// </summary>
        /// <param name="groupQuery">搜索条件</param>
        /// <param name="interestTopic">是否是查询可能感兴趣的专题</param>
        /// <returns>符合搜索条件的分页集合</returns>
        public PagingDataSet <TopicEntity> Search(TopicFullTextQuery groupQuery, bool interestTopic = false)
        {
            if (!interestTopic)
            {
                if (string.IsNullOrWhiteSpace(groupQuery.Keyword) && !groupQuery.KeywordIsNull)
                {
                    return(new PagingDataSet <TopicEntity>(new List <TopicEntity>()));
                }
            }

            LuceneSearchBuilder searchBuilder = BuildLuceneSearchBuilder(groupQuery, interestTopic);

            //使用LuceneSearchBuilder构建Lucene需要Query、Filter、Sort
            Query  query  = null;
            Filter filter = null;
            Sort   sort   = null;

            searchBuilder.BuildQuery(out query, out filter, out sort);

            //调用SearchService.Search(),执行搜索
            PagingDataSet <Document> searchResult = searchEngine.Search(query, filter, sort, groupQuery.PageIndex, groupQuery.PageSize);
            IEnumerable <Document>   docs         = searchResult.ToList <Document>();

            //解析出搜索结果中的专题ID
            List <long> groupIds = new List <long>();
            //获取索引中专题的标签
            Dictionary <long, IEnumerable <string> > groupTags = new Dictionary <long, IEnumerable <string> >();
            //获取索引中专题的分类名
            Dictionary <long, string> categoryNames = new Dictionary <long, string>();

            foreach (Document doc in docs)
            {
                long groupId = long.Parse(doc.Get(TopicIndexDocument.TopicId));
                groupIds.Add(groupId);
                groupTags[groupId]     = doc.GetValues(TopicIndexDocument.Tag).ToList <string>();
                categoryNames[groupId] = doc.Get(TopicIndexDocument.CategoryName);
            }

            //根据专题ID列表批量查询专题实例
            IEnumerable <TopicEntity> groupList = topicService.GetTopicEntitiesByIds(groupIds);

            foreach (var group in groupList)
            {
                if (groupTags.ContainsKey(group.TopicId))
                {
                    group.TagNames = groupTags[group.TopicId];
                }
                if (categoryNames.ContainsKey(group.TopicId))
                {
                    group.CategoryName = categoryNames[group.TopicId];
                }
            }

            //组装分页对象
            PagingDataSet <TopicEntity> TopicEntitys = new PagingDataSet <TopicEntity>(groupList)
            {
                TotalRecords  = searchResult.TotalRecords,
                PageSize      = searchResult.PageSize,
                PageIndex     = searchResult.PageIndex,
                QueryDuration = searchResult.QueryDuration
            };

            return(TopicEntitys);
        }
示例#19
0
        public ActionResult _InterestedWithAll(int pageSize = 6, int pageIndex = 1, string view = null)
        {
            IUser CurrentUser = UserContext.CurrentUser;

            if (CurrentUser == null)
            {
                return(null);
            }

            //查询同一公司的(优先级最高)
            Dictionary <long, IEnumerable <string> > companyNameDic = null;
            UserSearcher         userSearcher      = (UserSearcher)SearcherFactory.GetSearcher(UserSearcher.CODE);
            PagingDataSet <User> usersWithCompanys = userSearcher.SearchInterestedWithCompanys(CurrentUser.UserId, 1, 30, out companyNameDic);

            //存储感兴趣的人
            List <User> userList = usersWithCompanys.ToList();
            //存储感兴趣的类型
            Dictionary <long, string> interestedDic = usersWithCompanys.ToDictionary(key => key.UserId, value => "WithCompanys");

            //查询有共同关注用户的(优先级第二)
            Dictionary <long, IEnumerable <long> > followedUserIdDic = null;
            Dictionary <long, User> followedUserDic    = null;
            FollowUserSearcher      followUserSearcher = (FollowUserSearcher)SearcherFactory.GetSearcher(FollowUserSearcher.CODE);
            PagingDataSet <User>    usersWithFollows   = followUserSearcher.SearchInterestedWithFollows(CurrentUser.UserId, 1, 30, out followedUserIdDic, out followedUserDic);

            foreach (User user in usersWithFollows)
            {
                if (!interestedDic.ContainsKey(user.UserId))
                {
                    userList.Add(user);
                    interestedDic.Add(user.UserId, "WithFollows");
                }
            }

            //查询同一个学校的(优先级第三)
            Dictionary <long, IEnumerable <string> > schoolNameDic = null;
            PagingDataSet <User> usersWithSchools = userSearcher.SearchInterestedWithSchools(CurrentUser.UserId, 1, 30, out schoolNameDic);

            foreach (User user in usersWithSchools)
            {
                if (!interestedDic.ContainsKey(user.UserId))
                {
                    userList.Add(user);
                    interestedDic.Add(user.UserId, "WithSchools");
                }
            }

            //查询相同标签的(优先级最低)
            Dictionary <long, IEnumerable <string> > tagNameDic = null;
            PagingDataSet <User> usersWithTags = userSearcher.SearchInterestedWithTags(CurrentUser.UserId, 1, 30, out tagNameDic);

            foreach (User user in usersWithTags)
            {
                if (!interestedDic.ContainsKey(user.UserId))
                {
                    userList.Add(user);
                    interestedDic.Add(user.UserId, "WithTags");
                }
            }


            ViewData["followedUserIdDic"] = followedUserIdDic;
            ViewData["followedUserDic"]   = followedUserDic;
            ViewData["companyNameDic"]    = companyNameDic;
            ViewData["schoolNameDic"]     = schoolNameDic;
            ViewData["tagNameDic"]        = tagNameDic;
            ViewData["interestedDic"]     = interestedDic;

            //不指定View,则返回固定的页面,随机显示
            if (string.IsNullOrEmpty(view))
            {
                //随机从用户列表中取pageSize对应的对象组装成新的集合
                List <User> randomUserList = null;
                if (userList.Count <= pageSize)
                {
                    randomUserList = userList;
                }
                else
                {
                    Dictionary <int, User> randomUserDic = new Dictionary <int, User>();
                    Random random = new Random();

                    while (randomUserDic.Count < pageSize)
                    {
                        int index = random.Next(0, userList.Count);
                        if (!randomUserDic.ContainsKey(index))
                        {
                            User user = userList[index];
                            randomUserDic.Add(index, user);
                        }
                    }

                    randomUserList = randomUserDic.OrderBy(n => n.Key).Select(n => n.Value).ToList();
                }

                return(View(randomUserList));
            }
            //指定view,分页显示
            else
            {
                ViewData["pageCount"] = userList.Count / pageSize + 1;
                return(View(view, userList.Skip(pageSize * (pageIndex - 1)).Take(pageSize)));
            }
        }
示例#20
0
        /// <summary>
        /// 重建索引
        /// </summary>
        public void RebuildIndex()
        {
            //pageSize参数决定了每次批量取多少条数据进行索引。要注意的是,如果是分布式搜索,客户端会将这部分数据通过WCF传递给服务器端,而WCF默认的最大传输数据量是65535B,pageSize较大时这个设置显然是不够用的,WCF会报400错误;系统现在将最大传输量放宽了,但仍要注意一次不要传输过多,如遇异常,可适当调小pageSize的值
            bool     hasData         = true;
            int      pageSizeTags    = 1000;
            int      pageIndexTags   = 1;
            long     totalRecordTags = 0;
            bool     isBeginningTags = true;
            bool     isEnddingTags   = false;
            TagQuery tagQuery        = new TagQuery();

            do
            {
                PagingDataSet <Tag> tags = tagService.GetTags(tagQuery, pageIndexTags, pageSizeTags);
                totalRecordTags = tags.TotalRecords;
                if (totalRecordTags > 0)
                {
                    hasData = true;
                }
                isEnddingTags = (pageSizeTags * pageIndexTags < totalRecordTags) ? false : true;

                //重建索引
                List <Tag> tagList = tags.ToList <Tag>();

                IEnumerable <Document> docs = TagIndexDocument.Convert(tagList);

                searchEngine.RebuildIndex(docs, isBeginningTags, false);

                isBeginningTags = false;
                pageIndexTags++;
            }while (!isEnddingTags);

            int  pageSizeTagInOwner     = 1000;
            int  pageIndexTagInOwner    = 1;
            long totalRecordsTagInOwner = 0;
            bool isEnddingTagInOwner    = false;

            do
            {
                //分页获取帖子列表
                PagingDataSet <TagInOwner> tagInOwners = tagService.GetOwnerTags(pageIndexTagInOwner, pageSizeTagInOwner);
                totalRecordsTagInOwner = tagInOwners.TotalRecords;
                if (totalRecordsTagInOwner > 0)
                {
                    hasData = true;
                }
                isEnddingTagInOwner = (pageSizeTagInOwner * pageIndexTagInOwner < totalRecordsTagInOwner) ? false : true;

                //重建索引
                List <TagInOwner> tagInOwnerList = tagInOwners.ToList <TagInOwner>();

                IEnumerable <Document> docs = TagIndexDocument.Convert(tagInOwnerList);

                searchEngine.RebuildIndex(docs, false, false);

                pageIndexTagInOwner++;
            }while (!isEnddingTagInOwner);

            if (hasData)
            {
                searchEngine.RebuildIndex(null, false, true);
            }
        }
示例#21
0
        /// <summary>
        /// 日志分页搜索
        /// </summary>
        /// <param name="blogQuery">搜索条件</param>
        /// <returns>符合搜索条件的分页集合</returns>
        public PagingDataSet <BlogThread> Search(BlogFullTextQuery blogQuery)
        {
            if (blogQuery.SiteCategoryId == 0 && blogQuery.LoginId == 0 && blogQuery.UserId == 0)
            {
                if (string.IsNullOrWhiteSpace(blogQuery.Keyword) && blogQuery.IsRelationBlog == false)
                {
                    return(new PagingDataSet <BlogThread>(new List <BlogThread>()));
                }
            }

            LuceneSearchBuilder searchBuilder = BuildLuceneSearchBuilder(blogQuery);

            //使用LuceneSearchBuilder构建Lucene需要Query、Filter、Sort
            Query  query  = null;
            Filter filter = null;
            Sort   sort   = null;

            searchBuilder.BuildQuery(out query, out filter, out sort);

            //调用SearchService.Search(),执行搜索
            PagingDataSet <Document> searchResult = searchEngine.Search(query, filter, sort, blogQuery.PageIndex, blogQuery.PageSize);
            IEnumerable <Document>   docs         = searchResult.ToList <Document>();

            //解析出搜索结果中的日志ID
            List <long> blogThreadIds = new List <long>();
            //获取索引中日志的标签
            Dictionary <long, IEnumerable <string> > blogTags = new Dictionary <long, IEnumerable <string> >();
            //获取索引中日志的用户分类名
            Dictionary <long, IEnumerable <string> > blogOwnerCategoryNames = new Dictionary <long, IEnumerable <string> >();

            foreach (Document doc in docs)
            {
                long blogThreadId = long.Parse(doc.Get(BlogIndexDocument.ThreadId));
                blogThreadIds.Add(blogThreadId);
                blogTags[blogThreadId] = doc.GetValues(BlogIndexDocument.Tag).ToList <string>();
                blogOwnerCategoryNames[blogThreadId] = doc.GetValues(BlogIndexDocument.OwnerCategoryName).ToList <string>();
            }

            //根据日志ID列表批量查询日志实例
            IEnumerable <BlogThread> blogThreadList = blogThreadService.GetBlogThreads(blogThreadIds);

            foreach (var blogThread in blogThreadList)
            {
                blogThread.Body = blogThread.GetBody();
                if (blogTags.ContainsKey(blogThread.ThreadId))
                {
                    blogThread.TagNames = blogTags[blogThread.ThreadId];
                }
                if (blogOwnerCategoryNames.ContainsKey(blogThread.ThreadId))
                {
                    blogThread.OwnerCategoryNames = blogOwnerCategoryNames[blogThread.ThreadId];
                }
            }

            //组装分页对象
            PagingDataSet <BlogThread> blogThreads = new PagingDataSet <BlogThread>(blogThreadList)
            {
                TotalRecords  = searchResult.TotalRecords,
                PageSize      = searchResult.PageSize,
                PageIndex     = searchResult.PageIndex,
                QueryDuration = searchResult.QueryDuration
            };

            return(blogThreads);
        }
示例#22
0
        /// <summary>
        /// 搜索“毕业于同一学校”的用户/// </summary>
        /// <param name="userId">当前用户的ID</param>
        /// <param name="pageIndex">分页页码</param>
        /// <param name="pageSize">分页大小</param>
        /// <param name="schoolNameDic">存储用户ID到学校名称列表的映射,用于页面列表输出</param>
        /// <returns></returns>
        public PagingDataSet <User> SearchInterestedWithSchools(long userId, int pageIndex, int pageSize, out Dictionary <long, IEnumerable <string> > schoolNameDic)
        {
            //Dictionary,用于页面列表输出
            schoolNameDic = new Dictionary <long, IEnumerable <string> >();

            //无效用户ID,直接返回空列表
            if (userId <= 0)
            {
                return(new PagingDataSet <User>(new List <User>()));
            }

            Query  query  = null;
            Filter filter = null;
            Sort   sort   = null;

            //先搜索出当前用户的学校名称
            //使用LuceneSearchBuilder构建Lucene需要Query、Filter、Sort
            LuceneSearchBuilder searchBuilder = new LuceneSearchBuilder();

            searchBuilder.WithField(UserIndexDocument.UserId, userId.ToString(), true);
            searchBuilder.BuildQuery(out query, out filter, out sort);

            IEnumerable <Document> docs = searchEngine.Search(query, filter, sort, 1);

            //索引中无此用户,直接返回空列表
            if (docs == null || docs.Count() == 0)
            {
                return(new PagingDataSet <User>(new List <User>()));
            }

            string[] mySchoolNames = docs.First <Document>().GetValues(UserIndexDocument.School);

            //当前用户无学校,直接返回空列表
            if (mySchoolNames != null && mySchoolNames.Count() == 0)
            {
                return(new PagingDataSet <User>(new List <User>()));
            }

            //查找有相同学校名称的用户
            //先查询当前用户关注的人(包括“悄悄关注”的用户),此处需要调用数据库查询,因为索引中没有存储“是否悄悄关注”属性
            IEnumerable <long> myFollowedUserIds = followService.GetPortionFollowedUserIds(userId);
            //黑名单用户
            IEnumerable <long> stopUserIds = new PrivacyService().GetStopedUsers(userId).Select(n => n.Key);

            //使用LuceneSearchBuilder构建Lucene需要Query、Filter、Sort
            searchBuilder = new LuceneSearchBuilder(1);
            //搜索条件需要排除掉当前用户本身
            searchBuilder.WithPhrases(UserIndexDocument.School, mySchoolNames.Distinct().Take(3).ToList())
            .NotWithField(UserIndexDocument.UserId, userId.ToString())                            //排除掉当前用户
            .NotWithFields(UserIndexDocument.UserId, myFollowedUserIds.Select(n => n.ToString())) //排除掉已关注用户
            .NotWithFields(UserIndexDocument.UserId, stopUserIds.Select(n => n.ToString()));      //排除掉黑名单用户
            searchBuilder.BuildQuery(out query, out filter, out sort);

            PagingDataSet <Document> searchResult = searchEngine.Search(query, filter, sort, pageIndex, pageSize);

            docs = searchResult.ToList <Document>();

            //如果没有使用相同学校名称的用户,直接返回空列表
            if (docs == null || docs.Count() == 0)
            {
                return(new PagingDataSet <User>(new List <User>()));
            }

            //“相同学校名称”的用户ID列表
            List <long> sameUserIds = new List <long>();

            foreach (Document doc in docs)
            {
                //比较获取“相同的学校名称”
                List <string> sameSchoolNames = new List <string>();
                string[]      schoolNames     = doc.GetValues(UserIndexDocument.School);
                foreach (string mySchoolName in mySchoolNames)
                {
                    foreach (string schoolName in schoolNames)
                    {
                        if (schoolName.Equals(mySchoolName) || schoolName.Contains(mySchoolName))
                        {
                            sameSchoolNames.Add(mySchoolName);
                            break;
                        }
                    }
                }

                long sameUserId = long.Parse(doc.Get(UserIndexDocument.UserId));
                sameUserIds.Add(sameUserId);

                //加入Dictionary,用于页面列表输出
                if (!schoolNameDic.ContainsKey(sameUserId))
                {
                    schoolNameDic.Add(sameUserId, sameSchoolNames);
                }
            }

            //批量查询“相同学校名称”的用户列表
            IEnumerable <User> sameUsers = userService.GetFullUsers(sameUserIds).Where(n => n.IsCanbeFollow == true && n.IsActivated == true && n.IsBanned == false);

            //组装分页对象
            PagingDataSet <User> users = new PagingDataSet <User>(sameUsers)
            {
                TotalRecords  = searchResult.TotalRecords,
                PageSize      = searchResult.PageSize,
                PageIndex     = searchResult.PageIndex,
                QueryDuration = searchResult.QueryDuration
            };

            return(users);
        }
        /// <summary>
        /// 日志分页搜索
        /// </summary>
        /// <param name="journalQuery">搜索条件</param>
        /// <returns>符合搜索条件的分页集合</returns>
        public PagingDataSet <Journal> Search(JournalFullTextQuery journalQuery)
        {
            if (journalQuery.SiteCategoryId == 0 && journalQuery.LoginId == 0 && journalQuery.UserId == 0)
            {
                if (string.IsNullOrWhiteSpace(journalQuery.Keyword) && journalQuery.IsRelationJournal == false)
                {
                    return(new PagingDataSet <Journal>(new List <Journal>()));
                }
            }

            LuceneSearchBuilder searchBuilder = BuildLuceneSearchBuilder(journalQuery);

            //使用LuceneSearchBuilder构建Lucene需要Query、Filter、Sort
            Query  query  = null;
            Filter filter = null;
            Sort   sort   = null;

            searchBuilder.BuildQuery(out query, out filter, out sort);

            //调用SearchService.Search(),执行搜索
            PagingDataSet <Document> searchResult = searchEngine.Search(query, filter, sort, journalQuery.PageIndex, journalQuery.PageSize);
            IEnumerable <Document>   docs         = searchResult.ToList <Document>();

            //解析出搜索结果中的日志ID
            List <long> journalIds = new List <long>();
            //获取索引中日志的标签
            Dictionary <long, IEnumerable <string> > journalTags = new Dictionary <long, IEnumerable <string> >();
            //获取索引中日志的用户分类名
            Dictionary <long, IEnumerable <string> > journalOwnerCategoryNames = new Dictionary <long, IEnumerable <string> >();

            foreach (Document doc in docs)
            {
                long journalid = long.Parse(doc.Get(JournalIndexDocument.id));
                journalIds.Add(journalid);
                //journalTags[journalid] = doc.GetValues(JournalIndexDocument.Tag).ToList<string>();
                //journalOwnerCategoryNames[journalid] = doc.GetValues(JournalIndexDocument.OwnerCategoryName).ToList<string>();
            }

            //根据日志ID列表批量查询日志实例
            IEnumerable <Journal> journalList = journalService.GetJournalsByIds(journalIds);

            /*foreach (var journal in journalList)
             * {
             *  journal.Body = journal.GetBody();
             *  if (blogTags.ContainsKey(journal.ThreadId))
             *  {
             *      journal.TagNames = blogTags[journal.ThreadId];
             *  }
             *  if (journalOwnerCategoryNames.ContainsKey(journal.ThreadId))
             *  {
             *      journal.OwnerCategoryNames = journalOwnerCategoryNames[journal.ThreadId];
             *  }
             * }
             */
            //组装分页对象
            PagingDataSet <Journal> journals = new PagingDataSet <Journal>(journalList)
            {
                TotalRecords  = searchResult.TotalRecords,
                PageSize      = searchResult.PageSize,
                PageIndex     = searchResult.PageIndex,
                QueryDuration = searchResult.QueryDuration
            };

            return(journals);
        }
示例#24
0
        /// <summary>
        /// 重建索引
        /// </summary>
        public void RebuildIndex()
        {
            //pageSize参数决定了每次批量取多少条数据进行索引。要注意的是,如果是分布式搜索,客户端会将这部分数据通过WCF传递给服务器端,而WCF默认的最大传输数据量是65535B,pageSize较大时这个设置显然是不够用的,WCF会报400错误;系统现在将最大传输量放宽了,但仍要注意一次不要传输过多,如遇异常,可适当调小pageSize的值
            int       pageSize     = 1000;
            int       pageIndex    = 1;
            long      totalRecords = 0;
            bool      isBeginning  = true;
            bool      isEndding    = false;
            UserQuery query        = new UserQuery();

            do
            {
                Dictionary <long, dynamic> userDictionary = new Dictionary <long, dynamic>();

                //分页获取用户列表
                PagingDataSet <User> users = userService.GetUsers(query, pageSize, pageIndex);
                totalRecords = users.TotalRecords;

                isEndding = (pageSize * pageIndex < totalRecords) ? false : true;
                List <long> userIds = new List <long>();

                //以用户id为key,存入字典类
                foreach (User user in users.ToList <User>())
                {
                    //构建动态对象,用于存放用户搜索相关字段
                    dynamic dUser = new ExpandoObject();
                    dUser.UserId           = user.UserId;
                    dUser.UserName         = user.UserName;
                    dUser.TrueName         = user.TrueName;
                    dUser.NickName         = user.NickName;
                    dUser.DateCreated      = user.DateCreated;
                    dUser.LastActivityTime = user.LastActivityTime;

                    //初始化动态对象
                    dUser.Gender        = null;
                    dUser.Birthday      = null;
                    dUser.LunarBirthday = null;
                    dUser.BirthdayType  = null;
                    dUser.NowAreaCode   = null;
                    dUser.HomeAreaCode  = null;
                    dUser.AvatarImage   = null;
                    dUser.Introduction  = null;
                    dUser.Schools       = new List <string>();
                    dUser.CompanyNames  = new List <string>();
                    dUser.TagNames      = new List <string>();

                    dUser.AvatarImage = user.Avatar;
                    userDictionary.Add(user.UserId, dUser);
                    userIds.Add(user.UserId);
                }

                //根据用户id列表查询基本资料
                IEnumerable <UserProfile> userProfiles = userProfileService.GetUserProfiles(userIds);
                foreach (UserProfile userProfile in userProfiles)
                {
                    dynamic dUser = userDictionary[userProfile.UserId];
                    dUser.Gender        = userProfile.Gender;
                    dUser.Birthday      = userProfile.Birthday;
                    dUser.LunarBirthday = userProfile.LunarBirthday;
                    dUser.BirthdayType  = userProfile.BirthdayType;
                    dUser.NowAreaCode   = userProfile.NowAreaCode;
                    dUser.HomeAreaCode  = userProfile.HomeAreaCode;
                    dUser.Introduction  = userProfile.Introduction;
                }

                //根据用户id列表查询教育经历
                IEnumerable <long> educationExperienceIds = userProfileService.GetEducationExperienceIdsByUserIds(userIds);
                IEnumerable <EducationExperience> educationExperiences = userProfileService.GetEducationExperiences(educationExperienceIds);
                foreach (EducationExperience educationExperience in educationExperiences)
                {
                    dynamic dUser = userDictionary[educationExperience.UserId];
                    dUser.Schools.Add(educationExperience.School);
                }

                //根据用户id列表查询工作经历
                IEnumerable <long>           workExperienceIds = userProfileService.GetWorkExperienceIdsByUserIds(userIds);
                IEnumerable <WorkExperience> workExperiences   = userProfileService.GetWorkExperiences(workExperienceIds);
                foreach (WorkExperience workExperience in workExperiences)
                {
                    dynamic dUser = userDictionary[workExperience.UserId];
                    dUser.CompanyNames.Add(workExperience.CompanyName);
                }

                //根据用户id列表查询tags

                //fixed by jiangshl,修改了方法名,此处是为了性能考虑,以用户ID列表为参数,批量查询出对应的ItemInTag的ID,再批量查询出ItemInTag实体
                IEnumerable <long>      itemInTagIds = tagService.GetItemInTagIdsByItemIds(userIds);
                IEnumerable <ItemInTag> itemInTags   = tagService.GetItemInTags(itemInTagIds);
                foreach (ItemInTag itemInTag in itemInTags)
                {
                    dynamic dUser = userDictionary[itemInTag.ItemId];
                    dUser.TagNames.Add(itemInTag.TagName);
                }

                //重建索引
                List <dynamic> userList = new List <dynamic>();
                userList.AddRange(userDictionary.Values);

                IEnumerable <Document> docs = UserIndexDocument.Convert(userList);

                searchEngine.RebuildIndex(docs, isBeginning, isEndding);

                isBeginning = false;
                pageIndex++;
            }while (!isEndding);
        }