-1

Hello I want to get a specific key via TinyDB but I am only getting an empty result.

Here is a simple example of my db:

{"_default": {
  "1": {
    "1082685467876675736": "https://stackoverflow.com/"
  }
}}

Here I am trying to get the url for a specific pid (https://stackoverflow.com/ in this case):

db = TinyDB('db.json')
pid = 1082685467876675736
url= db.get(Query()[str(pid)])
print(url)

This returns an empty result. Please note: I never know the url. All I have for a query is the pid.

I would appreciate any help :)

Michael P
  • 603
  • 1
  • 5
  • 22
mxxim
  • 37
  • 4
  • Queries are made to search for values not for keys. So you should change yozr database layout to be able to query `pid == str(1082685467876675736)` and get a dictionary result wich also holds the url (like `"pid: 1082685467876675736, "url:"stackoverflow.com"}`. – Michael P Jul 28 '23 at 20:05

1 Answers1

0

What you trying to accomplish is to find an entry by a key name. But queries in databases were mostly build to find values on specific keys.

I see two options for your situation:

1. Redesign your database schema

If the pid is an important value for you to query for, don't store it as a key - store it as a value instead; like this:

{"_default": {
  "1": {
    "pid": "1082685467876675736",
    "url": "https://stackoverflow.com/"
  },
  "2": {
    # ...
  }
}}

Then you can easily query this document with:

db = TinyDB('db.json')
pid = 1082685467876675736
result = db.search( Query().pid == str(pid) )
print( result.get('url') )

2. Use the exists() query

As of the nature of NoSQL databases not every document has look the same. You are free to add or remove keys now and then from some of your documents. That said there may be a need of selecting a subset of document which have (or not have) a specific key.

As an example think of a database with blog posts. Some of them have comments (so the documents got the list of comments under the key comments). If you are interested in Posts with comments you could query them regardless of the content of the comments key (which is very useful).

In your example this one pid may not devide your data into groups. It is value which is diffrent and present on every document I guess. So exists() is not intended and far from best practice here.

However, this should work anyway:

db = TinyDB('db.json')
pid = 1082685467876675736
result = db.search( Query()[ str(pid) ].exists() )
print( result.get( str(pid) ) )
Michael P
  • 603
  • 1
  • 5
  • 22