示例#1
0
        /// <summary>
        ///  查询表中geo_type_col这一列的值距离中心点不超过一定距离的数据。
        /// </summary>
        /// <param name="client"></param>
        public static void GeoDistanceQuery(OTSClient client)
        {
            Console.WriteLine("\n Start GeoDistance query...");

            SearchQuery      searchQuery      = new SearchQuery();
            GeoDistanceQuery geoDistanceQuery = new GeoDistanceQuery();  // 设置查询类型为GeoDistanceQuery

            geoDistanceQuery.FieldName       = Geo_type_col;
            geoDistanceQuery.CenterPoint     = "10,11"; // 设置中心点
            geoDistanceQuery.DistanceInMeter = 10000;   // 设置到中心点的距离条件,不超过50米
            searchQuery.Query = geoDistanceQuery;

            SearchRequest searchRequest = new SearchRequest(TableName, IndexName, searchQuery);

            ColumnsToGet columnsToGet = new ColumnsToGet();

            columnsToGet.Columns = new List <string>()
            {
                Geo_type_col
            };                                                           //设置返回Col_GeoPoint这一列
            searchRequest.ColumnsToGet = columnsToGet;

            SearchResponse response = client.Search(searchRequest);

            Console.WriteLine(response.TotalCount);
            foreach (var row in response.Rows)
            {
                PrintRow(row);
            }
        }
示例#2
0
 public static GeoDistanceQuery BuildGeoDistanceQuery(Aliyun.TableStore.DataModel.Search.Query.GeoDistanceQuery query)
 {
     GeoDistanceQuery.Builder builder = GeoDistanceQuery.CreateBuilder();
     builder.SetFieldName(query.FieldName);
     builder.SetCenterPoint(query.CenterPoint);
     builder.SetDistance(query.DistanceInMeter);
     return(builder.Build());
 }
        public async Task <IEnumerable <GetUpcomingEventsQueryResult> > GetUpcomingEvents(GetUpcomingEventsQuery getUpcomingEventsQuery)
        {
            var geoDistanceQuery = new GeoDistanceQuery();

            geoDistanceQuery.Field("location");
            geoDistanceQuery.Latitude(getUpcomingEventsQuery.Latitude);
            geoDistanceQuery.Longitude(getUpcomingEventsQuery.Longitude);
            geoDistanceQuery.Distance($"{getUpcomingEventsQuery.Radius}km");

            var statusMatchQuery = new MatchQuery(EventStatuses.ACTIVE);

            statusMatchQuery.Field("status");

            var conjunctionQuery = new ConjunctionQuery(geoDistanceQuery, statusMatchQuery);

            if (!string.IsNullOrEmpty(getUpcomingEventsQuery.Keywords))
            {
                var subjectMatchQuery = new MatchQuery(getUpcomingEventsQuery.Keywords).Fuzziness(1);

                conjunctionQuery.And(subjectMatchQuery);
            }

            var searchParams = new SearchParams()
                               .Fields("*")
                               .Limit(10)
                               .Timeout(TimeSpan.FromMilliseconds(10000));

            var searchQuery = new SearchQuery
            {
                Query        = conjunctionQuery,
                Index        = "idx_geo_events",
                SearchParams = searchParams
            };

            var queryResult = await _eventsBucket.QueryAsync(searchQuery);

            var result = new List <GetUpcomingEventsQueryResult>();

            foreach (var hit in queryResult.Hits)
            {
                result.Add(new GetUpcomingEventsQueryResult
                {
                    EventId     = Guid.Parse(hit.Id),
                    Subject     = hit.Fields["subject"],
                    UrlKey      = hit.Fields["urlKey"],
                    Description = hit.Fields["description"],
                    Date        = DateTimeOffset.Parse(hit.Fields["date"].ToString())
                });
            }

            return(result);
        }
示例#4
0
        public static QueryContainer MakeGeoDistanceQuery(string distance, double latitude,
                                                          double longitude, Field distanceField, double boost = 1)
        {
            var geoDistanceQuery = new GeoDistanceQuery
            {
                Field        = distanceField,
                DistanceType = GeoDistanceType.Arc,
                Location     = new GeoLocation(latitude, longitude),
                Distance     = distance,
                Boost        = boost
            };

            return(geoDistanceQuery);
        }
示例#5
0
        public void Export_Omits_Field_If_Not_Provided()
        {
            var query = new GeoDistanceQuery()
                        .Longitude(1.5)
                        .Latitude(2.0)
                        .Distance("10mi");

            var expected = JsonConvert.SerializeObject(new
            {
                location = new [] { 1.5, 2.0 },
                distance = "10mi"
            }, Formatting.None);

            Assert.Equal(expected, query.Export().ToString(Formatting.None));
        }
示例#6
0
        public override async Task VisitAsync(TermNode node, IQueryVisitorContext context)
        {
            if (context.QueryType != QueryType.Query || !(context is IElasticQueryVisitorContext elasticContext) || !elasticContext.IsGeoPropertyType(node.Field))
            {
                return;
            }

            string location = _resolveGeoLocation != null ? await _resolveGeoLocation(node.Term).ConfigureAwait(false) ?? node.Term : node.Term;

            var query = new GeoDistanceQuery {
                Field = node.Field, Location = location, Distance = node.Proximity ?? Distance.Miles(10)
            };

            node.SetQuery(query);
        }
示例#7
0
        public void Export_ReturnsValidJson()
        {
            var query = new GeoDistanceQuery()
                        .Longitude(1.5)
                        .Latitude(2.0)
                        .Distance("10mi")
                        .Field("bar");

            var expected = JsonConvert.SerializeObject(new
            {
                location = new [] { 1.5, 2.0 },
                distance = "10mi",
                field    = "bar"
            }, Formatting.None);

            Assert.Equal(expected, query.Export().ToString(Formatting.None));
        }
        public IActionResult Point([FromBody] PointSearch point)
        {
            var query = new GeoDistanceQuery();

            query.Latitude(point.Latitude);
            query.Longitude(point.Longitude);
            query.Distance(point.DistanceWithUnits);
            var searchParams = new SearchParams()
                               // .Fields("geo", "name") // omitting because of bug NCBC-1651
                               .Limit(10)
                               .Timeout(TimeSpan.FromMilliseconds(10000));
            var searchQuery = new SearchQuery
            {
                Query        = query,
                Index        = "mygeoindex",
                SearchParams = searchParams
            };
            var results = _bucket.Query(searchQuery);

            var list = new List <GeoSearchResult>();

            foreach (var hit in results.Hits)
            {
                // *** this part shouldn't be necessary
                // the geo and name should come with the search results
                // but there's an SDK bug NCBC-1651
                var doc = _bucket.Get <dynamic>(hit.Id).Value;
                // ****************
                list.Add(new GeoSearchResult
                {
                    Latitude   = doc.geo.lat,
                    Longitude  = doc.geo.lon,
                    InfoWindow = new InfoWindow
                    {
                        Content = doc.name + "<br />" +
                                  doc.city + ", " +
                                  doc.state + " " +
                                  doc.country
                    }
                });
            }
            return(Ok(list));
        }
        public async Task <IActionResult> GetUpcomingEvents([FromQuery] GetUpcomingEventsRequest request)
        {
            var query = new GeoDistanceQuery();

            query.Field("location");
            query.Latitude(request.Latitude);
            query.Longitude(request.Longitude);
            query.Distance($"{request.Radius}km");

            var searchParams = new SearchParams()
                               .Fields("*")
                               .Limit(10)
                               .Timeout(TimeSpan.FromMilliseconds(10000));

            var searchQuery = new SearchQuery
            {
                Query        = query,
                Index        = "eventsgeoindex",
                SearchParams = searchParams
            };

            var searchQueryResults = await _bucket.QueryAsync(searchQuery);

            var result = new List <GetUpcomingEventsResponse>();

            foreach (var hit in searchQueryResults.Hits)
            {
                result.Add(new GetUpcomingEventsResponse
                {
                    Subject = hit.Fields["subject"],
                    Address = hit.Fields["address"],
                    Date    = hit.Fields["date"]
                });
            }

            return(Ok(result));
        }
示例#10
0
        public async Task <IEnumerable <LocationsSearchResult> > GetLocations(Location location, int maxDistance, int maxResults)

        {
            var elasticDefaultIndex = _configuration.GetValue <string>("ElasticDefaultIndex");

            var query = new GeoDistanceQuery
            {
                Field        = Infer.Field <ElasticResponse>(p => p.Geoip.location),
                DistanceType = GeoDistanceType.Arc,
                Location     = new GeoLocation(location.lat, location.lon),
                Distance     = $"{maxDistance}m"
            };

            var response = await _elasticClient.SearchAsync <ElasticResponse>(
                s => s.Index(elasticDefaultIndex).Query(q => query)
                .Size(maxResults));

            return(response.Documents.Select(o => new LocationsSearchResult()
            {
                Address = o.Address,
                Latitude = o.Geoip.location.lat,
                Longitude = o.Geoip.location.lon
            }));
        }
示例#11
0
        internal static QueryContainer SimpleQueryItem(Field field, EsValue query, EnQueryType queryType, double?boost)
        {
            switch (queryType)
            {
            case EnQueryType.Term:
                return(new TermQuery
                {
                    Field = field,
                    IsVerbatim = true,
                    Value = query.Value.ToString(),
                    Boost = boost
                });

            case EnQueryType.Prefix:
                return(new PrefixQuery
                {
                    Field = field,
                    Value = query.Value.ToString(),
                    Boost = boost
                });

            case EnQueryType.InWildCard:
                return(new WildcardQuery
                {
                    Field = field,
                    Value = string.Format("*{0}*", query.Value.ToString()),
                    Boost = boost
                });

            case EnQueryType.DateRange:
            {
                var q = new DateRangeQuery
                {
                    Field       = field,
                    GreaterThan = (DateTime)query.From,
                    Boost       = boost
                };
                if (query.To != null)
                {
                    q.LessThan = (DateTime)query.To;
                }
                return(q);
            }

            case EnQueryType.GreaterThan:
            {
                var q = new NumericRangeQuery
                {
                    Field       = field,
                    GreaterThan = Convert.ToDouble(query.From),
                    Boost       = boost
                };
                return(q);
            }

            case EnQueryType.LessThan:
            {
                var q = new NumericRangeQuery
                {
                    Field    = field,
                    LessThan = Convert.ToDouble(query.From),
                    Boost    = boost
                };
                return(q);
            }

            case EnQueryType.Range:
            {
                var q = new NumericRangeQuery
                {
                    Field       = field,
                    GreaterThan = Convert.ToDouble(query.From),
                    Boost       = boost
                };
                if (query.To != null)
                {
                    q.LessThan = Convert.ToDouble(query.To);
                }
                return(q);
            }

            case EnQueryType.DatePast:
            {
                var q = new DateRangeQuery
                {
                    Field    = field,
                    LessThan = ((DateTime)query.Value),
                    Boost    = boost
                };
                return(q);
            }

            case EnQueryType.DateFuture:
            {
                var q = new DateRangeQuery
                {
                    Field       = field,
                    GreaterThan = (DateTime)query.Value,
                    Boost       = boost
                };
                return(q);
            }

            case EnQueryType.Distance:
            {
                var areaQuery = (LocationArea)query.Value;
                var q         = new GeoDistanceQuery
                {
                    Field        = field,
                    Distance     = new Distance(areaQuery.Distance),
                    Location     = areaQuery.Center,
                    DistanceType = GeoDistanceType.Plane,
                    Boost        = boost
                };
                return(q);
            }

            default:
                return(new MatchQuery
                {
                    Field = field,
                    Query = query.Value.ToString(),
                    Fuzziness = Fuzziness.Auto,
                    Boost = boost
                });
            }
        }
示例#12
0
        public static List <User> SearchByTags(List <Knowledges> knowledges)
        {
            //if (elasticClient.IndexExists("people").Exists)
            //    elasticClient.DeleteIndex("people");


            //var createIndexResponse = elasticClient.CreateIndex("people", c => c
            //    .Mappings(m => m
            //        .Map<User>(mm => mm
            //            .AutoMap()
            //            .Properties(p => p
            //                .GeoPoint(g => g
            //                    .Name(n => n.UserDates.Location)
            //                )
            //            )
            //        )
            //    )
            //);
            var searchRequest1 = elasticClient.Search <User>(s =>
                                                             s.Query(q => q
                                                                     .MatchAll()
                                                                     ).Index("peoplev5"));

            List <QueryContainer> mustClauses = new List <QueryContainer>();


            //knowledges.ForEach(delegate (Knowledges knowledge)
            // {
            //     mustClauses.Add(new MatchQuery()
            //     {
            //         Field = new Field("userKnowledges.knowledges.value"),
            //         Query = knowledge.Value,
            //         Operator = Operator.Or
            //     });
            // });
            GeoDistanceQuery a = new GeoDistanceQuery
            {
                Boost            = 1.1,
                Name             = "named_query",
                Field            = new Field("location"),
                DistanceType     = GeoDistanceType.Arc,
                Location         = new Nest.GeoLocation(0, 0),
                Distance         = "2000m",
                ValidationMethod = GeoValidationMethod.IgnoreMalformed
            };

            mustClauses.Add(a);
            var searchRequest = new SearchRequest <User>("peoplev5")
            {
                Size  = 10,
                From  = 0,
                Query = new BoolQuery
                {
                    Should = mustClauses
                }
            };

            var searchResponse = elasticClient.Search <User>(searchRequest);

            return(searchResponse.Documents.Distinct().ToList());
        }