English 中文(简体)
TinyDB - The Matches() Query
  • 时间:2024-09-17

TinyDB - The matches() Query


Previous Page Next Page  

The matches() query matches the data from a JSON file with a given condition (in the form of a regular expression) and returns the results accordingly. It will return a blank value if the condition does not match with the data in the file.

Syntax

The syntax of TinyDB matches() is as follows −


db.search(Query().field.matches(regular expression))

Here, field represents the part of data that we want to access. Query() is the object created of our JSON table named student.

Let s understand how it works with the help of a couple of examples. We will use the same student database that we have used in all the previous chapters.

Example 1

Let s see how we can use matches() for full item search.


from tinydb import Query
student = Query()
db.search(student.st_name.matches( [aZ]* ))

This query will fetch all the rows −


[
   {
      "roll_number":1,
      "st_name":"elen",
      "mark":250,
      "subject":"TinyDB",
      "address":"delhi"
   },
   {
      "roll_number":2,
      "st_name":"Ram",
      "mark":[
         250,
         280
      ],
      "subject":[
         "TinyDB",
         "MySQL"
      ],
      "address":"delhi"
   },
   {
      "roll_number":3,
      "st_name":"kevin",
      "mark":[
         180,
         200
      ],
      "subject":[
         "oracle",
         "sql"
      ],
      "address":"keral"
   },
   {
      "roll_number":4,
      "st_name":"lakan",
      "mark":200,
      "subject":"MySQL",
      "address":"mumbai"
   },
   {
      "roll_number":5,
      "st_name":"karan",
      "mark":275,
      "subject":"TinyDB",
      "address":"benglore"
   }
]

Example 2

Let s see how we can use matches() for case-sensitive search.


from tinydb import Query
import re
student = Query()
db.search(student.st_name.matches( ram , flags=re.IGNORECASE))

This query will fetch the rows where the student name matches the string "ram". Observe that we have used a flag to ignore the case while matching the strings.


[{
    roll_number : 2,
    st_name :  Ram ,
    mark : [250, 280],
    subject : [ TinyDB ,  MySQL ],
    address :  delhi 
}]

Example 3

Let s see how we can use matches() for a particular item.


student = Query()
db.search(student.address.matches( keral ))

This query will fetch the rows where the address matches the string "keral".


[{ roll_number : 3,  st_name :  kevin ,  mark : [180, 200],  subject :
[ oracle ,  sql ],  address :  keral }]

Example 4

Let s see what matches() would return when it does not find a particular item −


student = Query()
db.search(student.address.matches( Ratlam ))

There are no rows where the "address" field matches the string "Ratlam", hence it will return a blank value −


[]
Advertisements