2

I made a database for a project and I want to be able to search the database for the value but better than just a simple == operation. For example, If someone types in "columbia" for the search, I want the dictionary that has "Columbia University " as the value for the "Affiliation" key for that specific person

frg100
  • 139
  • 1
  • 2
  • 9

1 Answers1

3

You can search using regular expressions:

>>> db.search(User.name.matches('[aZ]*'))
>>> db.search(User.name.search('b+'))

These correspond to Python's re.match and re.search where the latter searches for an occurenc that may start anywhere in the string.

Alternatively you can use a custom test expression like so:

>>> test_contains = lambda value, search: search in value
>>> db.search(User.name.test(test_contains, 'Columbia'))

For more details, refer to the relevant section of the TinyDB docs.

msiemens
  • 2,223
  • 1
  • 28
  • 38
  • Can you elaborate on the test_contains example? I've tried this as written and I end up with a NameError: name 's' is not defined – Aaron Ciuffo Feb 14 '19 at 20:48
  • 1
    Thanks for the hint, @AaronCiuffo! The second code example was wrong, it should be fixed now – msiemens Feb 15 '19 at 15:53