How to fix '400 Bad request' in half of my request to Elastic search?
Asked Answered
S

0

7

I'm using elastic search cloud with a single index that has a single document. I'm using @elastic/elasticsearch latest version. I'm calling elastic search from Firebase cloud functions.

Here is how my elastic client is initialized in cloud function

const { Client, errors } = require('@elastic/elasticsearch');
const elasticClient = new Client({
    cloud: {
        id: 'xxxxxxxx',
    },
    auth: {
        username: 'xxxx',
        password: 'xxxxxx'
    },
    maxRetries: 5,
    requestTimeout: 60000,
});

Here is cloud function that queries the elastic search

exports.stickerSearch = functions.runWith(runtimeOpts).https.onRequest(async (req, res) => {
    try {
        const searchQuery = req.query.query;
        const searchResult = await elasticClient.search(
            {
                index: "packs",
                from: 0,
                q: searchQuery,
                size: 20,
                sort: 'dataCreatedAt'
            });
        res.status(searchResult.statusCode).send(searchResult.body.hits);
    }
    catch (e) {        
        console.log("search error", e)
        res.status(200).send({ "total": { "value": 0, "relation": "eq" }, "max_score": null, "hits": [] });
    }
});

When I call this function via HTTP as GET requests with the same "query" param half of the function works as expected and return search results, another half just fails with the following error :

{ ResponseError: Response Error
    at IncomingMessage.response.on (/srv/node_modules/@elastic/elasticsearch/lib/Transport.js:287:25)
    at emitNone (events.js:111:20)
    at IncomingMessage.emit (events.js:208:7)
    at endReadableNT (_stream_readable.js:1064:12)
    at _combinedTickCallback (internal/process/next_tick.js:139:11)
    at process._tickDomainCallback (internal/process/next_tick.js:219:9)
  name: 'ResponseError',
  meta: 
   { body: '400 Bad Request',
     statusCode: 400,
     headers: { 'content-type': 'text/plain; charset=utf-8', connection: 'close' },
     warnings: null,
     meta: { 
        context: null,
        request: [Object],
        name: 'elasticsearch-js',
        connection: [Object],
        attempts: 0,
        aborted: false 
} } }

I have no idea why the same request fails sometimes.

Scad answered 31/8, 2019 at 21:33 Comment(3)
Please share the elasticsearch query (req.query.query) as this is probably the source of the error.Eldoria
@Eldoria it's just a simple keyword like "cat" or "test", nothing special. It completely works when I do the same query via direct REST API, but half request fails from Firebase Cloud Function with elastic JS SDK.Scad
can you share the exception or inner exceptions which would help us to find more info about the errorEquity

© 2022 - 2024 — McMap. All rights reserved.