Skip to content

Instantly share code, notes, and snippets.

@Kobnar
Last active January 8, 2023 18:28
Show Gist options
  • Select an option

  • Save Kobnar/0f027d99f1fb4033a9eed6d253c8ee4a to your computer and use it in GitHub Desktop.

Select an option

Save Kobnar/0f027d99f1fb4033a9eed6d253c8ee4a to your computer and use it in GitHub Desktop.
Enabling text search with MongoEngine.
from mongoengine import Document, StringField, IntField, BooleanField
class MockDocument(Document):
name = StringField(required=True, unique=True)
number = IntField()
fact = BooleanField()
meta = {
'allow_inheritance': True, # Triggers the issue
'indexes': [
{
'fields': ['$name'],
'cls': False # Solves the issue
}
]
}
import unittest
class MockDocumentIntegrationTests(unittest.TestCase):
TEST_DB = 'test'
@classmethod
def setUp(cls):
import mongoengine
db = mongoengine.connect(cls.TEST_DB)
db.drop_database(cls.TEST_DB)
def setUp(self):
from models import MockDocument
MockDocument.drop_collection()
def test_search_text_returns_matching_documents(self):
"""A search_text() query returns matching MockDocument instances
"""
names = [
'Some Important Document',
'Some Other Document',
'Another Important Document']
from ..models import MockDocument
for name in names:
MockDocument(name=name).save()
docs = MockDocument.objects.search_text('important').all()
expected = {
'Some Important Document',
'Another Important Document'}
results = {d.name for d in docs}
self.assertEqual(expected, results)
def test_raw_text_search_returns_matching_documents(self):
"""A raw text search query returns matching MockDocument instances
"""
names = [
'Some Important Document',
'Some Other Document',
'Another Important Document']
from ..models import MockDocument
for name in names:
MockDocument(name=name).save()
raw_query = {'$text': {'$search': 'important'}}
docs = MockDocument.objects(__raw__=raw_query).all()
expected = {
'Some Important Document',
'Another Important Document'}
results = {d.name for d in docs}
self.assertEqual(expected, results)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment