Couchdb query multiple keys get all docs by one of keys - python

I have a view in couchdb that returns results with two keys:
[<string_key>, <date>]
I need to ignore second key "date" and return all docs that matches key "string". But when I'm trying ignore the "date" key, view returns all values. Any advice?

You need to use startkey and endkey for doing this. You can ignore the second parameter by using {} in the end key. It returns all the possible results.
For reference you can look at the summary of this article: http://ryankirkman.com/2011/03/30/advanced-filtering-with-couchdb-views.html

Related

Django: Get one key and value from queryset dictionary

I have this query:
item = Item.objects.filter(id=3)
It is returning a queryset with its the keys and values.
Now I need to extract a particular value from the queryset, like this:
item_name = item['name']
But it does not work. How can I achieve this? Send the most simple way if possible, please. Thanks!
You have several wrong assumptions here.
A queryset is not a dict and does not have keys and values. It's a sequence of items, if anything most similar to a list.
I think what you want to do is to get a specific instance from the database, and access its fields. To get one instance you use get, not filter, as filter will always give you a queryset even if there is only a single match. Then, from that instance, you use attribute access not dict lookup. So:
item = Item.objects.get(id=3)
item_name = item.name
Here you can use the getattr function of python through which you can get your objective.
getattr(item, 'name')

dynamodb removing specific item from a list without collisions

I am using dynamodb with the python api, and have a list attribute, the list contains complex data in it.
I would like to be able to remove a specific item.
I found this tutorial explaining how to remove an item from the list by it's index.
And found this SO question regarding the situation.
Both the tutorial and the SO question show how to remove an item from a list by it's index, I have a more specific situation, where two users can use the same dynamodb table at once, and both of them might be trying to remove the same item, when using index, it can cause a situation as the following: having a list [1,2,3] two users want to remove the item "1" and using remove list[0], the first user removes the item 1, but now the list is [2,3] and the second user removes the item "2".
I found that you can remove a specific item by it's value when using dynamodb set datatype, but there is no set that can contain a complex data, only binary, str and number and I need to store something that is more like: {"att1":[1,2,3], "att2":str, "attr3":{...}} and nested.
How can I remove an item without the risk of removing another item by the index if someone already removed it before me causing me to remove the wrong item?
I don't remember exactly is dynamodb can return hash of the existing record
If not you can try to add it as additional field and create a key by this property
And then you can update your object with where clause
something like
aws dynamodb update-item \
--table-name ProductCatalog \
--key '{"myHash":{"N":"125948abcdef1234"}}' \
--update-expression
Idea is if object was already updated by someone hash also should be different

Use .contains() to retrieve values from DynamoDB

I'm new with NoSQL Databases and am stuck with a problem. I just want to get keys from a table in DynamoDB that contains a specific value. I know that for key equals I can use:
response = table.query(
KeyConditionExpression=Key('year').eq(1992)
)
But I can't use:
response = table.query(
KeyConditionExpression=Key('year').contain('1992')
)
The error is:
Key object has no attribute contain.
DynamoDB doesn't follow to use contain for key attribute on Query API. You can use only equals for partition key attribute.
CONTAINS can be used with LIST or SET data type only. Also, it can be used only on FilterExpression.
CONTAINS : Checks for a subsequence, or value in a set.
CONTAINS is supported for lists: When evaluating "a CONTAINS b", "a"
can be a list; however, "b" cannot be a set, a map, or a list.
People looking at this question in 2023 (At least with the current version of Boto!) are going to be misled to the other answers here.
You can now check if a value contains a substring by using the Attr object, not Key.
response = table.scan(
FilterExpression=Attr('key').contains(string)
)
Here you can check all the methods for Key class:
https://github.com/boto/boto3/blob/develop/boto3/dynamodb/conditions.py
Key class is inherited from class AttributeBase and here are nothing like contains, only greater than or starts with etc.

pymongo sort and find_one issue

I am trying to sort a collection called user_score using the key position and get the very first document of the result. In this case the collection user_score doesn't exist and I was hoping to get the result as None, but i was getting a cursor back.
1.
result =
db.user_score.find({'score':'$lt':score}}).sort("position,pymongo.DESCENDING").limit(1)
Now i changed my query like below and did not get anything as expected.
2.
result =
db.user_score.find_one({'score':{'$lt':score}}, sort=[("position", pymongo.DESCENDING)])
What's the problem with my first query?
Thanks
A little late in my response but it appears that the current version of PyMongo does support a sort operation on a find_one call.
From the documentation page here:
All arguments to find() are also valid arguments for find_one(),
although any limit argument will be ignored. Returns a single
document, or None if no matching document is found.
Example usage is as follows:
filterdict = {'email' : 'this.is#me.com'}
collection.find_one(filterdict, sort=[('lastseen', 1)])
Hope this helps more recent searchers!
In your first query, in the sort function you're passing one argument ("position,pymongo.DESCENDING"), when you should be passing two arguments ("position", pymongo.DESCENDING).
Be sure to mind your quotation marks.
This is the default mongodb behavior on find. Whenever you use find you get a list of the result (in this case an iterable cursor). Only findOne - or it's PyMongo equivalent find_one will return None if the query has no matches.
Use list to convert the value of the cursor into a dict:
list(db.user_score.find({'score':'$lt':score}}).sort("position",pymongo.DESCENDING).limit(1))[0]

Ordered Dictionary in Python: add to MongoDB

I have a list of two element tuples, where the first element is a string (name of some parameter) and the second element is a float (the value of that parameter). For example,
thelist = [('costperunit', 200), ('profit', 10000), ('fixedcost', 5000),
('numpeople':300)]
There are many more such tuples and the names are different in the real case. I want to add these to a mongoDB database as key: value pairs. Here is how I want to add it.
db.collection.insert( {paramvalues: {'costperunit':200, 'profit':10000,
'fixedcost': 5000, 'numpeople': 300} } )
One way to do this is:
dictform = dict(thelist)
db.collection.insert( {paramvalues: dictform} )
This, however, does not ensure the order of the parameter names and values as dict changes the order.
I tried
from collections import OrderedDict
dictform = OrderedDict(thelist)
db.collection.insert( {paramvalues: dictform} )
This maintains the original order of parameter names and values, however, inserts the parameter names and values as list of lists.
I am very new to mongoDB and trying to learn it. Is there a trick either in Python or in mongoDB that would achieve what I want? The reason I want the value of the key paramvalues in the Mongodb database as a dictionary (or Javascript object) is that I can then filter results using the value of some parameter. For example, I can do:
db.collection.find( {'paramvalues.costperunit': 200} )
If you are sure there is no way to do this, I would appreciate if you let me know.
Thanks.
Pymongo offers a subclass of dict, bson.son.SON: http://api.mongodb.org/python/current/api/bson/son.html which is ordered for cases where you need that such as sending commands.
Dicts in Python and arrays in Javascript/BSON (MongoDB) are not ordered. Either you store some explicit sort-index number as part of the dict/array and perform app-level sorting on this level or you insert your data into a list which is of course sorted.

Categories