Post request for bulk API is giving status code of 406, How to resolve it? - elasticsearch

I am using Elastic search 6.1 version
My data is appending correctly and I am adding '\n' at the end of the request.
My code is as follows:
def insert_in_bulk(self, filee, rtype):
U = urljoin(self.args.host, "/_bulk")
body = []
f = open(filee)
for line in f:
action = {
'index' :{
'_index' : self.args.index,
'_type' : rtype,
}
}
item = {
'word' : line.strip()
}
body.append(json.dumps(action))
body.append(json.dumps(item))
f.close()
body = '\n'.join(body)+'\n'
success = False
try:
r = requests.post(U, data=body)
self.log.info("after request")
if r.status_code == 200:
success = True
r = r.json()
self.log.info("inserted %s items of type = %s", self.args.index , rtype)
except (SystemExit, KeyboardInterrupt): raise
except:
self.log.exception("during bulk index")
if not success:
self.log.error("failed to index records of type = %s", rtype)
I am using the python to connect to elastic search.
I got the answer from this link
Bulk index document from JSON file into ElasticSearch
I have to pass the header to the request as application/x-ndjson.

Though it is quite some time question is asked, but i want to give a solution that has worked for me in most case,
def insert_in_bulk(self, filee, rtype):
U = urljoin(self.args.host, "/_bulk")
body = []
f = open(filee)
for line in f:
action = {
'index' :{
'_index' : self.args.index,
'_type' : rtype,
}
}
item = {
'word' : line.strip()
}
body.append(json.dumps(action))
body.append(json.dumps(item))
f.close()
payload = ""
for l in body:
payload = payload + f"{l} \n"
data = payload.encode('utf-8')
r = requests.post(U, data=data, headers={"Content-Type": "application/x-ndjson"})
print(r.text)

Related

Convert non typical json string to JSON

I'm fetching from a random API url and I'm getting a response like this one:
"key='jio3298', age=24, key='oijf032', age=62". How can I turn this non-json string into a list of JSON objects (i.e [{'key': 'jio3298', age: 24}, {'key':'oijf032', 'age':62}]) in an efficient way using JavaScript? I did get this code problem in an interview (one of the part of the problem. I needed that list to loop and filter based on a condition) and it seems my answer was at the very least slow.
you should use
String.prototype.split()
to create an array and then loop on this arry and create pears of key and value.
here an expmple:
const parser = (input) => {
input = input.split(",");
let keyAgeList = [],
output = [];
for (let i of input) {
i = i.replace("'", "");
i = i.replace(" ", "");
i = i.split("=");
if (i[0] === "key") {
keyAgeList[0] = i[1];
} else {
keyAgeList[1] = i[1];
}
if (keyAgeList.length > 1) {
let x = {
key: keyAgeList[0].replace("'", ""),
age: keyAgeList[1].replace("'", ""),
};
output.push(x);
keyAgeList = [];
}
}
console.log(JSON.stringify(output))
return JSON.stringify(output);
};
parser("key='jio3298', age=24, key='oijf032', age=62")

Error Implementing free dictionary Api in discord.py

I am trying to implement this api but the code says error every single time.
My code so far:
#client.command()
async def mean(ctx,word):
response = requests.get(f"https://api.dictionaryapi.dev/api/v2/entries/en/{word}")
if response.status_code == 404:
await ctx.send("No such word")
return
else:
wordx = response.json()
the_dictionary = wordx[0]
meanings = the_dictionary['meanings']
definitions = meanings[0]
definition = definitions['definitions']
meaningg = definition[0]
meaning = meaningg['definition']
example = meaningg.get('example',['None'])
synonymslist = meaningg.get("synonyms",['None'])
if isinstance(synonymslist,str):
synonymslist = [synonymslist]
pass
synonyms = ','.join(synonymslist)
deffinal= discord.Embed(title=f"`{word.upper()}`")
deffinal.add_field(name = "Definition", value=f"{meaning}")
deffinal.add_field(name = 'Example', value = f"{example}")
deffinal.add_field(name = "Synonyms", value = f"{synonyms}")
await ctx.channel.send(embed = deffinal)
Here is the error message:
Your error does not come from the API call to the dictionary api, but rather from your call to the discord api.
The error message says discord.errors.HTTPException: [...] In embed.fields.2.value: This field is required.
So the error comes from an empty field in your embed! The field has index 2 so it is actually the third field (Synonyms) which is causing the problem.
You can simply check if a string is empty, before even adding the field. And if it is empty, just don't add it.
deffinal= discord.Embed(title=f"`{word.upper()}`")
if meaning:
deffinal.add_field(name = "Definition", value=f"{meaning}")
if example:
deffinal.add_field(name = 'Example', value = f"{example}")
if synonyms:
deffinal.add_field(name = "Synonyms", value = f"{synonyms}")
#client.command()
async def mean(ctx,word):
response = requests.get(f"https://api.dictionaryapi.dev/api/v2/entries/en/{word}")
if response.status_code == 404:
await ctx.send("No such word")
return
else:
wordx = response.json()
the_dictionary = wordx[0]
meanings = the_dictionary['meanings']
definitions = meanings[0]
definition = definitions['definitions']
meaningg = definition[0]
meaning = meaningg['definition']
example = meaningg.get('example',['None'])
synonymslist = meaningg.get("synonyms",['None'])
if isinstance(synonymslist,str):
synonymslist = [synonymslist]
pass
synonyms = ','.join(synonymslist)
deffinal= discord.Embed(title=f"`{word.upper()}`")
if meaning:
deffinal.add_field(name = "Definition", value=f"{meaning}")
if example:
deffinal.add_field(name = 'Example', value = f"{example}")
if synonyms:
deffinal.add_field(name = "Synonyms", value = f"{synonyms}")
await ctx.channel.send(embed = deffinal)
Adding to itzFlubby answer, using requests will be blocking read more which means if you block for too long then your bot will freeze since it has not stopped the function’s execution at that point to do other things.
Here is the final code, also I changed the format a bit to make it easier to read.
# import aiohttp
#bot.command()
async def mean(ctx, word):
async with aiohttp.ClientSession() as session:
async with session.get(f"https://api.dictionaryapi.dev/api/v2/entries/en/{word}") as r:
if r.status == 200:
info = await r.json()
else:
return await ctx.reply("No such word")
the_dictionary = info[0]['meanings'][0]['definitions'][0]
definition = the_dictionary.get('definition')
example = the_dictionary.get('example')
synonymslist = the_dictionary.get("synonyms")
# if only one synonym is avaliable
if isinstance(synonymslist, str):
synonymslist = [synonymslist]
synonyms = '\n'.join(synonymslist)
deffinal = discord.Embed(title=f"`{word.upper()}`")
if definition:
deffinal.add_field(name="Definition", value=f"```{definition}```")
if example:
deffinal.add_field(name='Example', value=f"```{example}```")
if synonyms:
deffinal.add_field(name="Synonyms", value=f"```{synonyms}```")
await ctx.reply(embed=deffinal)

Grails controller: how render image from byte array

I have byte array byteImg but I want render in my controller jpeg from byte array:
def getSelfie = new HTTPBuilder()
getSelfie.request(fullSelfieUrl, GET, JSON) { req ->
headers.'X-DreamFactory-Session-Token' = session_id
headers.'X-DreamFactory-Application-Name' = 'checkReg'
response.success = { resp, reader ->
assert resp.statusLine.statusCode == 200
println "Get response: ${resp.statusLine}"
println "Content-Type: ${resp.headers.'Content-Type'}"
resp = reader as grails.converters.JSON
String str = resp.toString()
JSONObject jsonObject = new JSONObject(str)
selfieRend = jsonObject.getString("selfie")
byteImg = selfieRend.getBytes()
render byteImg
return byteImg
}
response.'404' = {
println 'Information not found'
}
}
how to do it? Thank you so much
I haven't tested it but as per wiki this should work:
def getSelfie(){
def http = new AsyncHTTPBuilder(
poolSize : 4,
uri : fullSelfieUrl,
contentType : ContentType.JSON )
def result = http.get() { resp, json -> json.selfie.bytes }
while( !result.done ) Thread.sleep 1000
def bytes = result.get()
response.setHeader 'Content-disposition', "inline; filename=someName.jpg"
response.setHeader 'Content-Type', 'image/jpg'
response.outputStream.withStream{ it << bytes }
}

grails ajax onload and oncomplete

can anyone give me sample coding that using grails ajax onload and oncomplete functions on following reader action? i want show a spinner icon while this action is onload and redirect to the list page while action is oncomplete..
def reader(){
def list = []
def dir = new File("C:/Users/User/Desktop/Summarize_20141212/HR_FILE")
dir.eachFileRecurse(FileType.FILES) { file ->
list << file
}
println list
list.each {
File file = new File(it.path)
def sql = groovy.sql.Sql.newInstance("jdbc:postgresql://localhost:5432/new",
'postgres', 'sa', "org.postgresql.Driver")
def lincoln = 0
file.eachLine() { line ->
if (line.trim().size() == 0) {
return null
} else {
def field = []
def tokens = line.split(',(?=([^\"]*\"[^\"]*\")*[^\"]*$)')
file.name.lastIndexOf('.').with { it != -1 ? file.name[0..<it] : file.name }
lincoln++
field.push(file.name)
for (String t : tokens) {
field.push(t)
}
while (field.size() < 10) {
field.push("")
}
if (lincoln > 1) {
sql.execute('insert into read_hr(version,col01,col02,col03,col04,col05,col06,col07,col08,col09,col10)' +
'VALUES (0,?,?,?,?,?,?,?,?,?,?)', field)
System.out.println(field);
}
}
}
}
redirect (action:"list")
}
These link will useful to you .
http://www.javacodegeeks.com/2013/05/grails-ajax-examples.html
http://javadeveloper.asia/grails-ajax-tutorial-remotelink-tag

Saving / Loading Images in Postgres using Anorm (Scala/PlayFramework 2)

I think I'm saving the image to Postgres correctly, but get unexpected results trying to load the image. I don't really know if the error is in save or load.
Here is my Anorm code for saving the image:
def storeBadgeImage(badgeHandle: String, imgFile: File) = {
val cmd = """
|update badge
|set img={imgBytes}
|where handle = {badgeHandle}
"""
var fis = new FileInputStream(imgFile)
var imgBytes: Array[Byte] = Resource.fromInputStream(fis).byteArray
// at this point I see the image in my browser if I return the imgBytes in the HTTP response, so I'm good so far.
DB.withConnection { implicit c =>
{
try {
SQL(cmd stripMargin).on("badgeHandle" -> badgeHandle, "imgBytes" -> imgBytes).executeUpdate() match {
case 0 => "update failed for badge " + badgeHandle + ", image " + imgFile.getCanonicalPath
case _ => "Update Successful"
}
} catch {
case e: SQLException => e.toString()
}
}
}
}
...I get "update succesful", so I presume the save is working (I could be wrong). Here is my code for loading the image:
def fetchBadgeImage(badgeHandle: String) = {
val cmd = """
|select img from badge
|where handle = {badgeHandle}
"""
DB.withConnection { implicit c =>
SQL(cmd stripMargin).on("badgeHandle" -> badgeHandle)().map {
case Row(image: Array[Byte]) => {
"image = " + image
}
case Row(Some(unknown: Any)) => {
println(unknown + " unknown type is " + unknown.getClass.getName) //[B#11be1c6 unknown type is [B
"unknown"
}
}
}
}
...rather than going into the case "Row(image: Array[Byte])" as hoped, it goes into the "Row(Some(unknown: Any))" case. My println outputs "[B#11be1c6 unknown type is [B"
I don't know what type [B is or where I may have gone wrong...
It's an array of byte in Java(byte[]). > "I don't know what type [B".
And You can write match { case Row(Some(image: Array[Byte])) => } too in this case and that might be better.
Or you might be able to do that as follows.
val results: Stream[Array[Byte]] = SQL(cmd stripMargin)
.on("badgeHandle" -> "name")().map { row => row[Array[Byte]]("img") }
...Oops, got the following compile error.
<console>:43: error: could not find implicit value for parameter c: anorm.Column[Array[Byte]]
val res: Stream[Array[Byte]] = SQL(cmd stripMargin).on("badgeHandle" -> "name")().map { row => row[Array[Byte]]("img") }
Unfortunately, scala.Array is not supported by default. If you imitate the way of other types, It works.
implicit def rowToByteArray: Column[Array[Byte]] = {
Column.nonNull[Array[Byte]] { (value, meta) =>
val MetaDataItem(qualified, nullable, clazz) = meta
value match {
case bytes: Array[Byte] => Right(bytes)
case _ => Left(TypeDoesNotMatch("..."))
}
}
}
val results: Stream[Array[Byte]] = SQL(cmd stripMargin)
.on("badgeHandle" -> "name")().map { row => row[Array[Byte]]("img") }
https://github.com/playframework/Play20/blob/master/framework/src/anorm/src/main/scala/anorm/Anorm.scala

Resources