예제 #1
0
        private static void SearchFileContent()
        {
            var data = GetFileData(AppDomain.CurrentDomain.BaseDirectory + @"files\ccflow.doc");

            var dataEncoding = Convert.ToBase64String(data); //转换为base64

            ElasticSearchHelper.Intance.Index("trying-out-mapper-attachments", "person", "1", new person2()
            {
                cv = dataEncoding
            });

            //查询文件内容

            string cmd   = new SearchCommand("trying-out-mapper-attachments", "person");
            var    query =
                new QueryBuilder <person2>().Query(
                    b =>
                    b.Bool(
                        m =>
                        m.Should(
                            q =>
                            q.QueryString(
                                qs =>
                                qs.Fields(new string[] { "cv" })
                                .Query("不支持低版本的IE浏览器")
                                .DefaultOperator(Operator.AND))))).Build();

            //文件内容查询结果
            var result = Client.Post(cmd, query);

            JsonNetSerializer serializer = new JsonNetSerializer();
            var list = serializer.ToSearchResult <person2>(result);
        }
예제 #2
0
        //全文检索,单个字段或者多字段 或关系
        //字段intro 包含词组key中的任意一个单词
        //
        public personList Search <person>(string indexName, string indexType, string key, int from, int size)
        {
            string cmd   = new SearchCommand(indexName, indexType);
            string query = new QueryBuilder <person>()
                           //1 查询
                           .Query(b =>
                                  b.Bool(m =>
                                         //并且关系
                                         m.Must(t =>

                                                //分词的最小单位或关系查询
                                                t.QueryString(t1 => t1.DefaultField("name").Query(key))
                                                //.QueryString(t1 => t1.DefaultField("name").Query(key))
                                                // t .Terms(t2=>t2.Field("intro").Values("研究","方鸿渐"))
                                                //范围查询
                                                // .Range(r =>  r.Field("age").From("100").To("200") )
                                                )
                                         )
                                  )
                           //分页
                           .From(from)
                           .Size(size)
                           //排序
                           .Sort(c => c.Field("updatetime", SortDirection.desc))
                           //添加高亮
                           .Highlight(h => h
                                      .PreTags("<b>")
                                      .PostTags("</b>")
                                      .Fields(
                                          f => f.FieldName("name").Order(HighlightOrder.score),
                                          f => f.FieldName("_all")
                                          )
                                      )
                           .Build();


            string     result     = Client.Post(cmd, query);
            var        serializer = new JsonNetSerializer();
            var        list       = serializer.ToSearchResult <person>(result);
            personList datalist   = new personList();

            datalist.hits = list.hits.total;
            datalist.took = list.took;
            //var personList = list.hits.hits.Select(c =>  person
            //{
            //    id = c._source.id,
            //    age = c._source.age,
            //    birthday = c._source.birthday,
            //    intro = string.Join("", c.highlight["intro"]), //高亮显示的内容,一条记录中出现了几次
            //    name = c._source.name,
            //    sex = c._source.sex,

            //});
            //datalist.list.AddRange(datalist);
            return(datalist);
        }
예제 #3
0
 public void Log(Event @event)
 {
     try
     {
         var eventS = _serializer.Serialize(@event);
         _connection.Post(new IndexCommand("log", "event"), eventS);
     }
     catch (Exception)
     {
     }
 }
예제 #4
0
파일: Program.cs 프로젝트: 1669561324/test2
        static void Main(string[] args)
        {
            ElasticConnection client = new ElasticConnection("localhost", 9200);
            SearchCommand     cmd    = new SearchCommand("movies", "电影");
            var query = new QueryBuilder <VerycdItem>()
                        .Query(b =>
                               b.Bool(m =>
                                      //并且关系
                                      m.Must(t =>
                                      //分词的最小单位或关系查询
                                             t.QueryString(t1 => t1.DefaultField("content").Query("成龙"))
                                             ).Must(t => t.QueryString(t1 => t1.DefaultField("category2").Query("纪录")))
                                      )
                               ).Size(100)
                        .Build();
            // DeleteCommand delCmd = new DeleteCommand()
            var result       = client.Post(cmd, query);
            var serializer   = new JsonNetSerializer();
            var searchResult = serializer.ToSearchResult <VerycdItem>(result);

            //searchResult.hits.total; //一共有多少匹配结果  10500
            // searchResult.Documents;//当前页的查询结果
            foreach (var doc in searchResult.Documents)
            {
                Console.WriteLine(doc.title + "," + doc.category1 + "," + doc.category2);
            }
            Console.ReadKey();
        }
예제 #5
0
파일: Program.cs 프로젝트: zxswola/ZH
        static void Main(string[] args)
        {
            ElasticConnection client = new ElasticConnection("localhost", 9200);
            SearchCommand     cmd    = new SearchCommand("MyTest", "persons");
            var query = new QueryBuilder <Person>().Query(b => b.Bool(m =>
                        //并且关系
                                                                      m.Must(t =>
                        //分词的最小单位或关系查询
                                                                             t.QueryString(t1 => t1.DefaultField("Name").Query("求")))))
                        //分页
                        //        .From(0)
                        //        .Size(10)
                        ////排序
                        //.Sort(c => c.Field("age", SortDirection.desc))
                        //////添加高亮
                        //.Highlight(h => h
                        //        .PreTags("<b>")
                        //        .PostTags("</b>")
                        //        .Fields(
                        //            f => f.FieldName("Name").Order(HighlightOrder.score))
                        //)
                        .Build();
            var result     = client.Post(cmd, query);
            var serializer = new JsonNetSerializer();
            var list       = serializer.ToSearchResult <Person>(result);

            foreach (var doc in list.Documents)
            {
                Console.WriteLine(doc.Id);
            }
        }
예제 #6
0
        public void Search()
        {
            BookHelper        bookHelper = new BookHelper();
            ElasticConnection client     = new ElasticConnection("222.186.190.241", 9200);
            //第一个参数是数据库,第二个参数是表
            SearchCommand cmd   = new SearchCommand("xiaoshuo", "xiaoshuo_url");
            var           query = new QueryBuilder <Book>()
                                  .Query(b =>
                                         b.Bool(m =>
                                                //并且关系
                                                m.Must(t =>
                                                //分词的最小单位或关系查询
                                                       t.QueryString(t1 => t1.DefaultField("Name").Query("总裁"))
                                                       )
                                                )
                                         ).Size(5).Build();
            var  result     = client.Post(cmd, query);
            var  count      = result.Result.Count();
            var  serializer = new JsonNetSerializer();
            var  results    = serializer.ToSearchResult <Book>(result); //把结果序列化
            Book book;

            foreach (var doc in results.Documents)
            {
                book = new Book()
                {
                    Name = doc.Name,
                    Url  = doc.Url
                };
                Console.WriteLine(book.Name);
                Console.WriteLine(book.Url);
            }
        }
예제 #7
0
        public List <Book> Search(string keyword)
        {
            ElasticConnection client = new ElasticConnection("222.186.190.241", 9200);
            //第一个参数是数据库,第二个参数是表
            SearchCommand cmd   = new SearchCommand("xiaoshuo", "xiaoshuo_url");
            var           query = new QueryBuilder <Book>()
                                  .Query(b =>
                                         b.Bool(m =>
                                                //并且关系
                                                m.Must(t =>
                                                //分词的最小单位或关系查询
                                                       t.QueryString(t1 => t1.DefaultField("Name").Query(keyword))
                                                       )
                                                )
                                         ).Size(5).Build();
            var         result     = client.Post(cmd, query);
            var         serializer = new JsonNetSerializer();
            var         results    = serializer.ToSearchResult <Book>(result); //把结果序列化
            List <Book> list       = new List <Book>();
            Book        book;

            foreach (var doc in results.Documents)
            {
                book = new Book()
                {
                    Name = doc.Name,
                    Url  = doc.Url
                };
                list.Add(book);
            }
            return(list);
        }
예제 #8
0
        /// <summary>
        /// elasticSearch(搜索下面方法中添加的数据)
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            ElasticConnection client = new ElasticConnection("localhost", 9200);
            SearchCommand     cmd    = new SearchCommand("verycd", "items");
            //首先创建我要查询的结果(VerycdItem)
            var query = new QueryBuilder <VerycdItem>()
                        .Query(b =>
                               b.Bool(m =>
                                      //并且关系
                                      m.Must(t =>
                                      //分词的最小单位或关系查询   //DefaultField是模糊匹配,Term是精确匹配(int,long类型),Must是必须(and),Should是或者(or),MustNot是否定(不能含有)
                                             t.QueryString(t1 => t1.DefaultField("content").Query("成龙"))
                                             ).Must(t => t.QueryString(t1 => t1.DefaultField("category2").Query("纪录")))
                                      )
                               ).Size(100)//默认返回10条,Size(100)表示返回最多100条
                        .Build();
            //elasticSearch中没有更新操作,先删在加
            // DeleteCommand delCmd = new DeleteCommand()
            //得到查询结果
            var result     = client.Post(cmd, query);
            var serializer = new JsonNetSerializer();
            //把查询结果序列化
            var searchResult = serializer.ToSearchResult <VerycdItem>(result);

            //searchResult.hits.total; //一共有多少匹配结果  10500
            // searchResult.Documents;//当前页的查询结果
            foreach (var doc in searchResult.Documents)
            {
                Console.WriteLine(doc.title + "," + doc.category1 + "," + doc.category2);
            }
            Console.ReadKey();
        }
예제 #9
0
        /// <summary>
        /// 全文检索
        /// </summary>
        /// <typeparam name="T">搜索类型</typeparam>
        /// <param name="indexName">索引名称</param>
        /// <param name="indexType">索引类型</param>
        /// <param name="query">查询条件(单个字段或者多字段或关系)</param>
        /// <param name="from">当前页(0为第一页)</param>
        /// <param name="size">页大小</param>
        /// <returns>搜索结果</returns>
        public SearchResult <T> Search <T>(string indexName, string indexType, QueryBuilder <T> query, int from, int size)
        {
            var queryString = query.From(from).Size(size).Build();

            var cmd = new SearchCommand(indexName, indexType);

            var result = Client.Post(cmd, queryString);

            var serializer = new JsonNetSerializer();

            return(serializer.ToSearchResult <T>(result));
        }
예제 #10
0
 public void RefreshIndex()
 {
     try
     {
         string searchCommand = Commands.Refresh(_esIndex);
         _connection.Post(searchCommand);
     }
     catch (Exception ex)
     {
         throw new Exception(string.Format("ES数据库挂了, 快找运维解决!{0}", ex.Message));
     }
 }
예제 #11
0
        /// <summary>
        /// 从ElasticSearch数据库中取数据(搜索)
        /// </summary>
        /// <param name="args"></param>
        static void Main2(string[] args)
        {
            //连接地址
            ElasticConnection client = new ElasticConnection("localhost", 9200);
            //从哪个数据库哪个表取数据
            SearchCommand cmd = new SearchCommand("zsz", "persons");
            //首先创建我要查询的结果(Person)
            var query = new QueryBuilder <Person>()
                        //查询的条件
                        .Query(b =>
                               b.Bool(m =>
                                      //并且关系
                                      m.Must(t =>
                                             //分词的最小单位或关系查询            //name字段中必须含有帅这个词
                                             t.QueryString(t1 => t1.DefaultField("Name").Query("丑"))
                                             )
                                      )
                               )
                        //分页(第0条开始取10条数据)

                        /*
                         * .From(0)//Skip()
                         * .Size(10)//Take()*/
                        //排序(根据年龄排序)
                        //.Sort(c => c.Field("Age", SortDirection.desc))
                        //添加高亮(查询结果高亮显示)

                        /*
                         * .Highlight(h => h
                         * .PreTags("<b>")
                         * .PostTags("</b>")
                         * .Fields(
                         *   f => f.FieldName("Name").Order(HighlightOrder.score)
                         *   )
                         * )*/
                        .Build();
            //查询结果
            var result     = client.Post(cmd, query);
            var serializer = new JsonNetSerializer();
            //把查询结果序列化
            var searchResult = serializer.ToSearchResult <Person>(result);

            //searchResult.hits.total; //一共有多少匹配结果  10500
            // searchResult.Documents;//当前页的查询结果
            foreach (var doc in searchResult.Documents)
            {
                Console.WriteLine(doc.Id + "," + doc.Name + "," + doc.Age);
            }
            Console.ReadKey();
        }
예제 #12
0
        public BaseQueryEntity <T> QueryInTerm(string field, string value)
        {
            string cmd   = CreateSearchCommand();
            string query = new QueryBuilder <T>()
                           .Query(q =>
                                  q.Filtered(f =>
                                             f.Filter(f1 =>
                                                      f1.Term(t =>
                                                              t.Field(field).Value(value))))).Build();
            OperationResult result = Client.Post(cmd, query);
            var             data   = serializer.ToSearchResult <T>(result.Result);

            return(GetResults(data));
        }
예제 #13
0
파일: Program.cs 프로젝트: PirateX0/ZSZ
        static void Main(string[] args)
        {
            ElasticConnection client = new ElasticConnection("localhost", 9200);
            SearchCommand     cmd    = new SearchCommand("zsz", "persons");
            var query = new QueryBuilder <Person>()
                        .Query(b =>
                               b.Bool(m =>
                                      //并且关系
                                      m.Must(t =>
                                      //分词的最小单位或关系查询
                                             t.QueryString(t1 => t1.DefaultField("Name").Query("hand"))
                                             )
                                      )
                               ).Size(100)
                        //分页

                        /*
                         * .From(0)//Skip()
                         * .Size(10)//Take()*/
                        //排序
                        //.Sort(c => c.Field("Age", SortDirection.desc))

                        //添加高亮

                        /*
                         * .Highlight(h => h
                         * .PreTags("<b>")
                         * .PostTags("</b>")
                         * .Fields(
                         *   f => f.FieldName("Name").Order(HighlightOrder.score)
                         *   )
                         * )*/
                        .Build();
            var result       = client.Post(cmd, query);
            var serializer   = new JsonNetSerializer();
            var searchResult = serializer.ToSearchResult <Person>(result);

            //searchResult.hits.total; //一共有多少匹配结果  10500
            // searchResult.Documents;//当前页的查询结果
            foreach (var doc in searchResult.Documents)
            {
                Console.WriteLine(doc.Id + "," + doc.Name + "," + doc.Age);
            }
            Console.ReadKey();
        }
예제 #14
0
        //ES搜索
        public ActionResult EsSearch(string Msg)
        {
            //从Es中查数据
            //模糊查询
            ElasticConnection client = new ElasticConnection("localhost", 9200);
            SearchCommand     cmd    = new SearchCommand("ZSZHouse", "House");//要查询的数据库,表名字
            var query = new QueryBuilder <HouseAddnewDTO>()
                        .Query(b =>
                               b.Bool(m =>
                                                                                                        //并且关系
                                      m.Must(t =>
                                                                                                        //分词的最小单位或关系查询
                                             t.QueryString(t1 => t1.DefaultField("Address").Query(Msg)) //title字段必须含有“美女”
                                             )
                                      )
                               )
                        .Build();
            var result       = client.Post(cmd, query);
            var serializer   = new JsonNetSerializer();
            var searchResult = serializer.ToSearchResult <HouseAddnewDTO>(result);
            //searchResult.hits.total;//一共有多少匹配结果
            //searchResult.Documents;//当前页的查询结果

            IndexHouseSearchViewModel model = new IndexHouseSearchViewModel();

            foreach (var doc in searchResult.Documents)
            {
                var r = doc.Address;
                model.Address = r;
                if (r.Contains(Msg))
                {
                    return(Json(new AjaxResult {
                        Status = "ok"
                    }));
                }
            }
            return(Json(new AjaxResult {
                Status = "error"
            }));
        }
예제 #15
0
        private static long CountTweets(ElasticConnection connection, JsonNetSerializer serializer)
        {
            string countCommand = Commands.Count("twitter", "tweet").Pretty();


            //string query = new QueryBuilder<Tweet>()
            //    .Query(qry => qry
            //        .Term(term => term
            //            .Field(tweet => tweet.User)
            //            .Value("testUser".ToLower()) // by default terms query requires lowercased values.
            //            .Boost(5)
            //         )
            //    ).BuildBeautified();

            string query = new QueryBuilder <Tweet>()
                           .Query(qry => qry
                                  .Term(t => t
                                        .Field(x => x.User)
                                        .Value("testuser")
                                        .Boost(5)
                                        )
                                  ).BuildBeautified(); // or .Buid(); to get condensed single line query.

            /* or alternatively
             * query = new TermQuery<Tweet>()
             *              .Field(x => x.User)
             *              .Value("testuser")
             *              .BuildBeautified();  // or .Buid(); to get condensed single line query.
             */

            var results = connection.Post(countCommand, query);

            var searchResult = serializer.ToCountResult(results);

            PrintCountResults(searchResult, countCommand, query, results);

            return(searchResult.count);
        }