コード例 #1
0
        protected override void SetArgument(string name, BsonValue value)
        {
            switch (name)
            {
            case "map":
                _map = BsonJavaScript.Create(value);
                return;

            case "reduce":
                _reduce = BsonJavaScript.Create(value);
                return;

            case "out":
                _options.OutputOptions = value is BsonString
                        ? new MapReduceOutputOptions.CollectionOutput(value.AsString, MapReduceOutputMode.Replace)
                        : MapReduceOutputOptions.Inline; // TODO: Clean this up.
                return;

            case "session":
                _session = (IClientSessionHandle)_objectMap[value.AsString];
                return;
            }

            base.SetArgument(name, value);
        }
コード例 #2
0
        public void setScoreByClass(string testname, string number, string classs, double score)
        {
            var name = getTestAddr(testname);
            var col  = mcon.GetCollection("Score:" + name);

            if (!col.Exists())//没有这个集合时新建&索引
            {
                Basic.trace(testname + " 试卷的第一名上交学生。");
                var str = BsonJavaScript.Create("addIndexForScore(" + name.ToJson() + ")");
                mcon.Eval(EvalFlags.None, str);
//                使用C#驱动建立索引
//                var indexKey = new IndexKeysBuilder();
//                indexKey.Ascending("score");
//                var indexOption = new IndexOptionsBuilder();
//                col.CreateIndex(indexKey, indexOption);
            }
            col.Save
            (
                new BsonDocument
            {
                { "_id", number },
                { "classs", classs },
                { "score", score }
            }
            );
            DbBasic.rwHt[name] = DbBasic.STAGE_WRITE;
        }
コード例 #3
0
ファイル: Document.cs プロジェクト: zhujinhu21/MongoCola
 /// <summary>
 ///     Save Edited Javascript
 /// </summary>
 /// <param name="jsName"></param>
 /// <param name="jsCode"></param>
 /// <param name="jsCol"></param>
 /// <returns></returns>
 public static string SaveEditorJavascript(string jsName, string jsCode, MongoCollection jsCol)
 {
     //标准的JS库格式未知
     if (QueryHelper.IsExistByKey(jsName))
     {
         //var result = DropDocument(jsCol, (BsonString) jsName);
         //if (string.IsNullOrEmpty(result))
         //{
         CommandResult resultCommand;
         try
         {
             resultCommand = new CommandResult(
                 jsCol.Save(new BsonDocument().Add(ConstMgr.KeyId, jsName)
                            .Add("value", BsonJavaScript.Create(jsCode))).Response);
         }
         catch (MongoCommandException ex)
         {
             resultCommand = new CommandResult(ex.Result);
         }
         if (resultCommand.Response["ok"] == 1)
         {
             return(string.Empty);
         }
         return(resultCommand.Response.Contains("err") ? resultCommand.Response["err"].ToString() : string.Empty);
         //}
         //return result;
     }
     return(string.Empty);
 }
コード例 #4
0
        public List <StatInfo> getStat(String testname)
        {
            List <StatInfo> list = new List <StatInfo>();;
            MongoCollection collection;
            var             name = getTestAddr(testname);

            System.Diagnostics.Debug.WriteLine(name);
            if ((DbBasic.rwHt[name] as int?) == DbBasic.STAGE_READ)//处于读阶段时,尝试直接读取数据库中的统计结果
            {
                System.Diagnostics.Debug.WriteLine("尝试从数据库获取试卷 " + testname + " 的统计结果");
                collection = mcon.GetCollection("StatResult:" + name);
                if (collection != null)
                {
                    try
                    {
                        list = collection.FindAllAs <StatInfo>().ToList();
                    }
                    catch (Exception e)
                    {
                        Basic.trace(e.StackTrace);
                    }
                    if (list.Count() != 0)
                    {
                        return(list);
                    }
                }
            }
            //处于写阶段时、没有统计结果时,使用mapreduce进行统计
            System.Diagnostics.Debug.WriteLine("数据库进行试卷 " + testname + " 的分数统计");
            collection = mcon.GetCollection("Score:" + name);
            String map    = "function(){emit(this.classs,this.score)}";
            String map2   = "function(){emit('总体',this.score)}";
            String reduce = "function(key , values){var result = renewStat2(key , values," + name.ToJson() + ");return result;}";

            MapReduceArgs args = new MapReduceArgs();

            args.MapFunction          = BsonJavaScript.Create(map);
            args.ReduceFunction       = BsonJavaScript.Create(reduce);
            args.OutputCollectionName = ("StatResult:" + name);
            args.OutputDatabaseName   = mcon.Name;
            //            args.OutputMode = MapReduceOutputMode.Replace;
            //            args.OutputMode = MapReduceOutputMode.Inline;
            args.OutputMode = MapReduceOutputMode.Merge;

            var md = collection.MapReduce(args);
            var ms = md.GetResultsAs <StatInfo>();

            list = ms.ToList();

            args.MapFunction = BsonJavaScript.Create(map2);
            md = collection.MapReduce(args);
            ms = md.GetResultsAs <StatInfo>().ToList();
            list.Concat(ms);
            //                                foreach (var i in mresult.GetResultsAs<StatInfo>()) list.Add(i.convertToJson());
            DbBasic.rwHt[name] = DbBasic.STAGE_READ;
            return(list);
        }
コード例 #5
0
        public BsonArray getScore(string testname, string classs)
        {
            System.Diagnostics.Debug.WriteLine("从数据库获取试卷{0}的{1}的学生分数", testname, classs);
            var name   = getTestAddr(testname);
            var js     = BsonJavaScript.Create(String.Format("getStudents('{0}','{1}')", name, classs));
            var result = mcon.Eval(EvalFlags.NoLock, js);

            return(result.AsBsonArray);
        }
コード例 #6
0
        /// <summary>
        /// 查询groupby数据
        /// </summary>
        /// <typeparam name="T">数据类型</typeparam>
        /// <param name="keys">主键列表</param>
        /// <param name="collectionName">表名</param>
        /// <param name="query">查询</param>
        /// <param name="filter">查询条件</param>
        /// <param name="javascriptReduce">脚本</param>
        /// <param name="javascriptFinalize">脚本2</param>
        /// <returns>查询groupby数据</returns>
        public IEnumerable <BsonDocument> QueryGroupby <T>(string[] keys, string collectionName, IMongoQuery query, BaseFilter filter,
                                                           string javascriptReduce, string javascriptFinalize)
        {
            MongoCollection collection     = GetMongoCollection(collectionName);
            GroupByBuilder  groupbyBuilder = new GroupByBuilder(keys);
            BsonDocument    doc            = new BsonDocument();

            return(collection.Group(query, groupbyBuilder, doc, BsonJavaScript.Create(javascriptReduce), BsonJavaScript.Create(javascriptFinalize)));
        }
コード例 #7
0
        public List <MusicInfo> SearchLibrary(string term)
        {
            var query = Query.Or(
                Query.Where(BsonJavaScript.Create(string.Format("this.Title.toLowerCase().indexOf('{0}') >= 0", term.ToLower()))),
                Query.Where(BsonJavaScript.Create(string.Format("this.Album.toLowerCase().indexOf('{0}') >= 0", term.ToLower()))),
                Query.Where(BsonJavaScript.Create(string.Format("this.Artist.toLowerCase().indexOf('{0}') >= 0", term.ToLower())))
                );

            return(MongoHelper.Current.GetCollection <MongoMusicInfo>("musicinfo")
                   .FindAs <MongoMusicInfo>(query)
                   .Take(30)
                   .ToList <MusicInfo>());
        }
コード例 #8
0
 public MapReduceResult executeMapReduce(string table, IMongoQuery query, string map_js, string reduce_js)
 {
     try
     {
         var            cb     = check_table(table);
         BsonJavaScript map    = BsonJavaScript.Create(map_js);
         BsonJavaScript reduce = BsonJavaScript.Create(reduce_js);
         var            ret    = cb.MapReduce(query, map, reduce);
         if (ret.Ok)
         {
             return(ret);
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
     return(null);
 }
コード例 #9
0
        public IInfo getScoreNumber(String testname, String classs = "all")
        {
            MongoCollection collection;
            var             name = getTestAddr(testname);

            if ((DbBasic.rwHt[name] as int?) == DbBasic.STAGE_READ)//处于读阶段时,尝试直接读取数据库中的统计结果
            {
                collection = mcon.GetCollection("ChartStat");
                var query = Query.And(Query.EQ("_id", classs), Query.EQ("test", name));
                var tmp   = collection.FindOneAs <ScoreNumberInfo>(query);
                if (tmp != null)
                {
                    return(tmp);
                }
            }
            //处于写阶段时、没有统计结果时,调用数据库的StatScoreNumber2函数进行分数段人数统计
            collection = mcon.GetCollection("ChatStat");
            var str    = String.Format("StatScoreNumber2('{0}','{1}')", name, classs);
            var tmp2   = mcon.Eval(EvalFlags.NoLock, BsonJavaScript.Create(str));
            var result = JsonConvert.DeserializeObject <ScoreNumberInfo>(tmp2.ToJson());

            collection.Save(tmp2);
            return(result);
        }
コード例 #10
0
        /// <summary>
        /// 客户任务调度统计
        /// </summary>
        /// <returns></returns>
        private Dictionary <string, int> GetCustomerJobInfo()
        {
            Dictionary <string, int> result = new Dictionary <string, int>();
            var col = new MongoOperation().GetCollection("BackgroundJob");
            Dictionary <string, int> dicInitial = new Dictionary <string, int>();

            dicInitial["count"] = 0;
            var r = col.Group(
                Query.And(Query.NE("customerCode", null), Query.NE("customerCode", ""), Query.Exists("customerCode", true)),
                "customerCode",
                BsonDocument.Create(dicInitial),
                BsonJavaScript.Create("function(doc,prev){prev.count++;}"),
                null
                ).ToList();

            if (r.Count > 0)
            {
                foreach (var item in r)
                {
                    result.Add(item.Text("customerCode"), item.Int("count"));
                }
            }
            return(result);
        }
コード例 #11
0
        public static BsonValue Create(this BsonType bsonType, object o)
        {
            BsonValue value = BsonNull.Value;

            try
            {
                switch (bsonType)
                {
                case BsonType.EndOfDocument:
                    break;

                case BsonType.Double:
                    value = BsonDouble.Create(o);
                    break;

                case BsonType.String:
                    value = BsonString.Create(o);
                    break;

                case BsonType.Document:
                    value = BsonDocument.Create(o);
                    break;

                case BsonType.Array:
                    value = BsonArray.Create(o);
                    break;

                case BsonType.Binary:
                    value = BsonBinaryData.Create(o);
                    break;

                case BsonType.Undefined:
                    break;

                case BsonType.ObjectId:
                    value = BsonObjectId.Create(o);
                    break;

                case BsonType.Boolean:
                    value = BsonBoolean.Create(o);
                    break;

                case BsonType.DateTime:
                    value = BsonDateTime.Create(o);
                    break;

                case BsonType.Null:
                    value = BsonNull.Value;
                    break;

                case BsonType.RegularExpression:
                    value = BsonRegularExpression.Create(o);
                    break;

                case BsonType.JavaScript:
                    value = BsonJavaScript.Create(o);
                    break;

                case BsonType.Symbol:
                    value = BsonSymbol.Create(o);
                    break;

                case BsonType.JavaScriptWithScope:
                    value = BsonJavaScriptWithScope.Create(o);
                    break;

                case BsonType.Int32:
                    value = BsonInt32.Create(o);
                    break;

                case BsonType.Timestamp:
                    value = BsonTimestamp.Create(o);
                    break;

                case BsonType.Int64:
                    value = BsonInt64.Create(o);
                    break;

                case BsonType.MaxKey:
                    value = BsonValue.Create(o);
                    break;

                case BsonType.MinKey:
                    value = BsonValue.Create(o);
                    break;
                }
            }
            catch
            {
            }

            return(value);
        }
コード例 #12
0
ファイル: AdmController.cs プロジェクト: x55756016/kmproject
        public IHttpActionResult Get([FromUri] Request <Info> request)
        {
            if (request.Type == -1)
            {
                MongoCollection          data           = database.GetCollection("info");
                GroupByBuilder           groupbyBuilder = new GroupByBuilder(new string[] { "CategoryCode", "CategoryName" });
                Dictionary <string, int> dic_F          = new Dictionary <string, int>();
                dic_F["num"] = 0;
                var result_F = data.Group(null, groupbyBuilder, BsonDocument.Create(dic_F), BsonJavaScript.Create("function(doc,prev){prev.num++;}"), BsonJavaScript.Create("function(doc){doc.Count=doc.num;delete doc.num;}")).ToList();

                /*List<InfoAllList> list = new List<InfoAllList>();
                 * if (result_F.Count > 0)
                 * {
                 *  foreach (var item in result_F)
                 *  {
                 *      InfoAllList temp = new InfoAllList();
                 *      temp.CategoryCode = item["CategoryCode"].AsString;
                 *      temp.CategoryName = item["CategoryName"].AsString;
                 *      temp.Count = item["Count"].AsDouble.ToString().ToInt(0);
                 *      list.Add(temp);
                 *  }
                 * }*/
                Response <List <BsonDocument> > rsp = new Response <List <BsonDocument> >();
                rsp.Data = result_F;
                return(Ok(rsp));
            }
            if (request.ID == "SearchInfo")
            {
                Response <List <InfoModel> > rsp = new Response <List <InfoModel> >();
                if (string.IsNullOrEmpty(request.Keyword))
                {
                    return(Ok(rsp));
                }

                List <InfoModel> list = new List <InfoModel>();

                #region 1、在mongodb查询匹配的Info对象
                IMongoQuery query = null;
                if (request.UserName == "Title")
                {
                    query = Query <Info> .Matches(c => c.Title, new BsonRegularExpression(new Regex(request.Keyword + ".*")));
                }
                else if (request.UserName == "Author")
                {
                    query = Query <Info> .Matches(c => c.Author, new BsonRegularExpression(new Regex(request.Keyword + ".*")));
                }
                else if (request.UserName == "Source")
                {
                    query = Query <Info> .Matches(c => c.Source, new BsonRegularExpression(new Regex(request.Keyword + ".*")));
                }
                else if (request.UserName == "Digest")
                {
                    query = Query <Info> .Matches(c => c.Digest, new BsonRegularExpression(new Regex(request.Keyword + ".*")));
                }
                else if (request.UserName == "KeyWord")
                {
                    query = Query <Info> .Matches(c => c.KeyWord, new BsonRegularExpression(new Regex(request.Keyword + ".*")));
                }
                else if (request.UserName == "CategoryCode")
                {
                    query = Query <Info> .Matches(c => c.CategoryCode, new BsonRegularExpression(new Regex(request.Keyword)));
                }

                if (query != null)
                {
                    var data = database.GetCollection("info").Find(query).ToList();
                    foreach (var item in data)
                    {
                        InfoModel temp = new InfoModel();
                        temp.InfoId = item.GetValue("_id").ToString();
                        temp.Title  = item.GetValue("Title").ToString();
                        Dictionary dic = getArticleClassNameFoo(item.GetValue("CategoryCode").ToString());
                        if (dic != null)
                        {
                            temp.ArticleClass = dic.value;
                        }
                        temp.ArticleCategory = item.GetValue("CategoryName").ToString();
                        temp.Author          = item.GetValue("Author").ToString();
                        string   extStr = item.GetValue("ArticleType").ToString();
                        string[] arr    = extStr.Split('、');
                        if (arr.Length > 0)
                        {
                            temp.FileType = arr[0];
                        }
                        else
                        {
                            temp.FileType = "1176708";
                        }

                        string fileUrl    = "";
                        string dbFileName = item.GetValue("FileName").AsString.Trim();
                        if (!string.IsNullOrEmpty(dbFileName))
                        {
                            fileUrl = "/Upload/" + dbFileName;
                        }

                        /*if (item.GetValue("FileName").ToString().Trim().EndsWith(".xls") || item.GetValue("FileName").ToString().Trim().EndsWith(".xlsx"))
                         * {
                         *  fileUrl += "XLS/";
                         * }
                         * fileUrl += item.GetValue("FileId").ToString().Trim() + "/" + item.GetValue("FileName").ToString().Trim();*/
                        temp.FilePath    = fileUrl;
                        temp.PublishTime = item.GetValue("PublishTime").AsDateTime;
                        temp.ArticleType = item.GetValue("ArticleType").AsString;
                        temp.ModifyTime  = item.GetValue("ModifyTime").AsDateTime;
                        temp.ModifyUser  = item.GetValue("ModifyUser").AsString;

                        list.Add(temp);
                    }
                }
                #endregion

                if (request.UserName == "Content")
                {
                    #region 2、查询solr服务器来搜索文件内容
                    string      q      = "text:" + request.Keyword;
                    string      url    = SolrUrl + "select?q=" + HttpUtility.UrlEncode(q) + "&rows=1000000&wt=json&_=" + StringExtension.getTimeStamp(DateTime.Now);
                    HttpClient  client = new HttpClient();
                    string      result = client.GetStringAsync(url).Result;
                    SolrContext sc     = result.JsonDeserialize <SolrContext>();
                    #endregion

                    #region 3、通过solr搜索结果来匹配数据库
                    foreach (var item in sc.response.docs)
                    {
                        FileInfo fi      = new FileInfo(item.uri);
                        string   dirName = fi.Directory.Name;
                        var      query2  = Query.EQ("FileId", dirName);
                        Info     info    = database.GetCollection("info").FindAs <Info>(query2).FirstOrDefault();
                        if (info == null)
                        {
                            continue;
                        }
                        if (info.FileName != fi.Name)
                        {
                            continue;
                        }

                        InfoModel temp = new InfoModel();
                        temp.InfoId = info._id.ToString();
                        temp.Title  = info.Title;
                        Dictionary dic = getArticleClassNameFoo(info.CategoryCode);
                        if (dic != null)
                        {
                            temp.ArticleClass = dic.value;
                        }
                        temp.ArticleCategory = info.CategoryName;
                        temp.Author          = info.Author;

                        string   extStr = info.ArticleType;
                        string[] arr    = extStr.Split('、');
                        if (arr.Length > 0)
                        {
                            temp.FileType = arr[0];
                        }
                        else
                        {
                            temp.FileType = "1176708";
                        }

                        string fileUrl = "/Upload/";
                        if (fi.Extension == ".xls" || fi.Extension == ".xlsx")
                        {
                            fileUrl += "XLS/";
                        }
                        fileUrl      += info.FileId + "/" + info.FileName;
                        temp.FilePath = fileUrl;

                        if (list.Contains(temp))
                        {
                            continue;
                        }
                        list.Add(temp);
                    }
                    #endregion
                }

                rsp.Data = list;
                if (request.UserName == "CategoryCode")
                {
                    List <InfoModel> result = list.Skip((request.CurrentPage - 1) * PageSize).Take(PageSize).ToList();
                    int count = list.Count / PageSize;
                    if (list.Count % PageSize > 0)
                    {
                        count += 1;
                    }
                    rsp.PagesCount = count;
                    rsp.Data       = result;
                }

                return(Ok(rsp));
            }
            else
            {
                Guid g = new Guid();
                if (Guid.TryParse(request.Keyword, out g))
                {
                    Dictionary    dic     = _dictionary.GetDictionaryById(g.ToString());
                    List <string> nodeIds = new List <string>();
                    nodeIds.Add(dic.nodeId);
                    Foo(nodeIds, dic);

                    Response <List <Info> > response = new Response <List <Info> >();
                    var         list   = database.GetCollection <Info>("info").FindAll().ToList();
                    List <Info> result = new List <Info>();
                    foreach (string item in nodeIds)
                    {
                        Info temp = list.Find(p => p.CategoryCode == item);
                        if (temp != null)
                        {
                            result.Add(temp);
                        }
                    }
                    response.Data = result;
                    return(Ok(response));
                }
                else
                {
                    Response <List <Info> > response = new Response <List <Info> >();
                    var list = database.GetCollection <Info>("info").FindAll().ToList();
                    if (!string.IsNullOrEmpty(request.Keyword))
                    {
                        list = list.FindAll(p => p.Title.Contains(request.Keyword) || p.Html.Contains(request.Keyword) || p.Author.Contains(request.Keyword));
                    }
                    response.Data = list;
                    return(Ok(response));
                }
            }
        }