Issue in updating elastic search field - python

This how my result source looks like.
{"_source": {"Name": "Where's My Crown Angry birds 3","movie_id":69}}
I need to update the Name field as "'Where's My Crown'". I used the following query:
{"script": {"inline": "ctx._source.Name='Where's My Crown'","lang": "painless"},"query": {"match": {"movie_id": 69}}}
But I got this error:
{'type': 'illegal_argument_exception', 'reason': "unexpected token ['s'] was expecting one of [{<EOF>, ';'}]."}**
Please help me to fix this.

This is because of the fact that there is a single quote in "Where's My Crown" and that interferes with the single quotes around the whole string.
Consider doing it like this (using params) instead:
{
"script": {
"inline": "ctx._source.Name = params.newName",
"params": {
"newName": "Where's My Crown"
},
"lang": "painless"
},
"query": {"match": {"movie_id": 69}}
}

I tried the solution below and it also worked for me:
Replace
'Where's My Crown'
with
\"Where's My Crown\"
So in my case (in JavaScript, not Python, but I think it would work similarly):
const script = Object.entries(newBody).reduce((prev, [key, value]) => {
return `${prev} ctx._source.${key}=\"${value}\";`;
}, '');

Related

Update nested Python list key using pop

I have a json file called pool.json which contains this:
{
"pools": {
"$poolId": {
"nodes": {
"$nodeId": {
"bcm": {
"address": {
"ip": "10.10.10.10"
},
"password": "ADMIN",
"username": "ADMIN"
}
}
}
}
}
}
This is my Python code:
pool_id = ['123456']
json_pool = json.loads(read_json_file('pool.json'))
for i in pool_id:
json_pool['pools'][i] = json_pool.pop(['pools']['$poolId'])
print('json_pool: %s' % json_pool)
I'm trying to update $poolId with the value in pool_id(I know I've only got one pool_id. I just want to get this piece working before I do anything else). Ive been trying to do this with pop but am having no success when it's nested as in this case. I can get it working when I want to change a top level key. What am I doing wrong?
I think you want to execute json_pool['pools'].pop('$poolId') instead of json_pool.pop(['pools']['$poolId']).

How to fix 'parse error on (VAR_SIGN)' in a graphql query in python

I am having trouble with GraphQL queries made in python. It says that the signal $ that determine a variable in the query cannot be parsed.
Error message:
{"errors":[{"message":"Parse error on \"$\" (VAR_SIGN) at [3, 3]","locations":[{"line":3,"column":3}]}]}
Is there other way to use variables in this kind of request?
Here is my query, I didn't paste the fragment because I think it's not the problem
query ApplicationIndexQuery(
$status: Boolean!
$page: Int
$perPage: Int
$filters: ApplicationFilter
$sort: String
) {
allOpportunityApplication(page: $page, per_page: $perPage, filters: $filters, sort: $sort) {
...ApplicationList_list
}
}
variables = {
"status": True,
"page": 1,
"perPage": 517,
"filters": {
"date_realized": {
"from": "2018-12-01",
"to": "2019-03-31"
},
"person_home_mc": 1535,
"programmes": 5
}
query should be at the top level, but it seems like in your example it's enclosed in curly braces. See below:
https://github.com/apollographql/graphql-tag/issues/180#issuecomment-386540792

Pymongo: Unable to find record from mongodb

I have a collection containing country records, I need to find particular country with uid and it's countryId
Below is the sample collection data:
{
"uid": 15024,
"countries": [{
"countryId": 123,
"popullation": 45000000
},
{
"countryId": 456,
"poppulation": 9000000000
}
]
},
{
"uid": 15025,
"countries": [{
"countryId": 987,
"popullation": 560000000
},
{
"countryId": 456,
"poppulation": 8900000000
}
]
}
I have tried with below query in in python but unable to find any result:
foundRecord = collection.find_one({"uid" : 15024, "countries.countryId": 456})
but it return None.
Please help and suggest.
I think following will work better :
foundRecord = collection.find_one({"uid" : 15024,
"countries" : {"$elemMatch" : { "countryId" : 456 }})
Are you sure you're using the same Database / Collection source?
Seems that you're saving results on another collection.
I've tried to reproduce your problem and it works on my mongodb ( note that I'm using v4)
EDIT: Would be nice to have the piece of code where you're defining "collection"

Accessing nested objects with python

I have a response that I receive from foursquare in the form of json. I have tried to access the certain parts of the object but have had no success. How would I access say the address of the object? Here is my code that I have tried.
url = 'https://api.foursquare.com/v2/venues/explore'
params = dict(client_id=foursquare_client_id,
client_secret=foursquare_client_secret,
v='20170801', ll=''+lat+','+long+'',
query=mealType, limit=100)
resp = requests.get(url=url, params=params)
data = json.loads(resp.text)
msg = '{} {}'.format("Restaurant Address: ",
data['response']['groups'][0]['items'][0]['venue']['location']['address'])
print(msg)
Here is an example of json response:
"items": [
{
"reasons": {
"count": 0,
"items": [
{
"summary": "This spot is popular",
"type": "general",
"reasonName": "globalInteractionReason"
}
]
},
"venue": {
"id": "412d2800f964a520df0c1fe3",
"name": "Central Park",
"contact": {
"phone": "2123106600",
"formattedPhone": "(212) 310-6600",
"twitter": "centralparknyc",
"instagram": "centralparknyc",
"facebook": "37965424481",
"facebookUsername": "centralparknyc",
"facebookName": "Central Park"
},
"location": {
"address": "59th St to 110th St",
"crossStreet": "5th Ave to Central Park West",
"lat": 40.78408342593807,
"lng": -73.96485328674316,
"labeledLatLngs": [
{
"label": "display",
"lat": 40.78408342593807,
"lng": -73.96485328674316
}
],
the full response can be found here
Like so
addrs=data['items'][2]['location']['address']
Your code (at least as far as loading and accessing the object) looks correct to me. I loaded the json from a file (since I don't have your foursquare id) and it worked fine. You are correctly using object/dictionary keys and array positions to navigate to what you want. However, you mispelled "address" in the line where you drill down to the data. Adding the missing 'a' made it work. I'm also correcting the typo in the URL you posted.
I answered this assuming that the example JSON you linked to is what is stored in data. If that isn't the case, a relatively easy way to see exact what python has stored in data is to import pprint and use it like so: pprint.pprint(data).
You could also start an interactive python shell by running the program with the -i switch and examine the variable yourself.
data["items"][2]["location"]["address"]
This will access the address for you.
You can go to any level of nesting by using integer index in case of an array and string index in case of a dict.
Like in your case items is an array
#items[int index]
items[0]
Now items[0] is a dictionary so we access by string indexes
item[0]['location']
Now again its an object s we use string index
item[0]['location']['address]

Python Falcon filtering through URL

I have a small API that i'm working on, everything works ok, all my requests do what they are supposed to but when I try to filter results through the URL query for some reason it works for id but not for device field.
def on_get(self, req, resp):
"""Handles GET requests"""
if req.get_param("id"):
result = {'location': r.db(PROJECT_DB).table(PROJECT_TABLE).get(req.get_param("id")).run(db_connection)}
elif req.get_param("device"):
result = {'location': r.db(PROJECT_DB).table(PROJECT_TABLE).get(req.get_param("device")).run(db_connection)}
else:
location = r.db(PROJECT_DB).table(PROJECT_TABLE).run(db_connection)
result = {'locations': [i for i in location]}
resp.body = json.dumps(result)
example http://localhost:8000/location?id=(some random id) this will work
but if i do http://localhost:8000/location?device=(some device) this will not work, returns null
So could anyone tell me what am I doing wrong? or better yet if anyone knows a better way to filter using the URL?
Note: I am using rethinkdb
EDIT:
This is what I have normally:
{
"locations": [
{
"id": "4bf4b94f-747a-42db-9d54-a8399d995025",
"location": "gps coords",
"device": "Device 2"
},
{
"id": "b5cce561-37d2-42e7-86e4-a31c008b0af2",
"location": "gps coords",
"device": "Device 1"
},
{
"id": "bebba7cf-710c-4ee8-ad69-2d58174d4e02",
"location": "gps coords",
"device": "Device 1"
},
{
"id": "e928f84b-60ff-40f3-b839-920bc99e5480",
"location": "gps coords",
"device": "Device1"
}
]
}
Filtering by id works ok, but not by device which is weird
I found the answer to this problem, the reason why it did not war was because rethinkdb only gets via primary key on the get query
result = {'location': r.db(PROJECT_DB).table(PROJECT_TABLE).get(req.get_param("device")).run(db_connection)}
so what I should have done was to filter the results by what I wanted like this and it would have worked
result = {'location': list(r.db(PROJECT_DB).table(PROJECT_TABLE).filter({'device': param}).run(db_connection))}
Thanks for the help everyone and hope this answer helps.

Categories