简体   繁体   中英

How to do a text search on the query set returned by a geospatial query in mongoengine?

I need to find 'items' nearby matching a text. I am using mongo engine and I have tried the following.

Item.objects(
            location__near=[item_obj.longitude, item_obj.latitude],
            location__max_distance=item_obj.range).filter(
                Q(title__icontains=item_obj.search) |
                Q(description__icontains=item_obj.search)
            ).order_by('-like_count')

I get the following error

OperationFailure: database error: can't find any special indices: 2d (needs index), 2dsphere (needs index),  for: { $and: [ { location: { $near: { $geometry: { type: "Point", coordinates: [ 4.95, 4.95 ] } }, $maxDistance: 10000 } }, { $or: [ { title: /title/i }, { description: /title/i } ] } ] }

However the following works just fine:

items = Item.objects(
                location__near=[item_obj.longitude, item_obj.latitude],
                location__max_distance=item_obj.range
            )

Here location is a PointField

Seems its not using the index for the query.

1) Ensure the index is created:

Item.ensure_indexes()

2) Add a hint to the query to ensure it uses the 2dsphere index:

Item.objects( 
  location__near=[item_obj.longitude, item_obj.latitude], 
  location__max_distance=item_obj.range).filter( 
    Q(title__icontains=item_obj.search) | 
    Q(description__icontains=item_obj.search) 
).order_by('-like_count').hint([('location', '2dsphere')])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM