Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Text Search? #102

Closed
tonybaloney opened this issue Aug 29, 2021 · 3 comments
Closed

Text Search? #102

tonybaloney opened this issue Aug 29, 2021 · 3 comments
Labels

Comments

@tonybaloney
Copy link
Contributor

tonybaloney commented Aug 29, 2021

I couldn't find anything in the docs to do text search (https://docs.mongodb.com/manual/reference/operator/query/text/)

I have a document :

class Location(Document):

    name: str
    private: bool = False

    class Meta:
        table = "locations"

I want to do a search like "where name contains 'New York'"

Is this possible at the moment?

@roman-right
Copy link
Member

roman-right commented Aug 29, 2021

For this you need a text index.

Here is the MongoDB doc: https://docs.mongodb.com/manual/core/index-text/
Beanie doc: https://roman-right.github.io/beanie/tutorial/indexes-%26-collection-names/#indexes

The simplest way to add it is:

class Location(Document):
    name: Indexed(str, index_type=TEXT)
    private: bool = False

    class Collection:
        name = "locations"

Then you can use operator Text or native MongoDB query.

Full working example:

import asyncio

from motor.motor_asyncio import AsyncIOMotorClient
from pymongo import TEXT

from beanie import Document, Indexed, init_beanie
from beanie.operators import Text

MONGO_URI = "YOUR URI"


class Location(Document):
    name: Indexed(str, index_type=TEXT)
    private: bool = False

    class Collection:
        name = "locations"


async def main():
    db = AsyncIOMotorClient(MONGO_URI).test_db
    await init_beanie(database=db, document_models=[Location])

    # await Location(name="some test New York bla bla").insert()
    # await Location(name="some test bla bla").insert()

    l = await Location.find(Text("New York")).to_list()
    print(l)


asyncio.run(main())

Thank you for the issue. I'll add this point to the doc.

@github-actions
Copy link

This issue is stale because it has been open 30 days with no activity.

@github-actions github-actions bot added the Stale label Mar 26, 2023
@github-actions
Copy link

This issue was closed because it has been stalled for 14 days with no activity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants