Elasticsearch-php: Add helper function to escape query

Created on 18 Aug 2017  路  9Comments  路  Source: elastic/elasticsearch-php

As per https://stackoverflow.com/questions/33845230/escape-elasticsearch-special-characters-in-php it would be nice with an 'official' and maintained function to help escape reserved characters

8.0 enhancement

Most helpful comment

A function like this works:

function escapeElasticReservedChars($query) {
    return preg_replace(
        '/[\\+\\-\\=\\&\\|\\!\\(\\)\\{\\}\\[\\]\\^\\\"\\~\\*\\<\\>\\?\\:\\\\\\/]/',
        addslashes('\\$0'),
        $query
    );
}

Found here: https://stackoverflow.com/a/33846134

All 9 comments

I'm not against such a thing, but I must admit I'm a bit confused what they are trying to escape? Field names? Index names? Characters in query string?

E.g. you can absolutely have braces ({) in an index name and a query_string query. You can have & in query_string but not index name. OR is a reserved term in query_string but unimportant anywhere else, etc etc.

That list just looks like a random collection to me :)

To your question though, we could maybe consider a function escape query_string strings. There's no such escaping for index or field names though, as Elasticsearch rejects the character itself and there's no way to escape it.

I was thinking escaping characters in a query_string

Ah gotcha. That's doable. I'll add something when I get a chance, unless you want to submit a PR first :)

If someone is going to implement this, just keep in mind

https://www.elastic.co/guide/en/elasticsearch/reference/5.5/query-dsl-query-string-query.html

< and > can鈥檛 be escaped at all. The only way to prevent them from attempting to create a range query is to remove them from the query string entirely.

So, the answer from Stackoverflow might be not 100% correct

I would love this

A function like this works:

function escapeElasticReservedChars($query) {
    return preg_replace(
        '/[\\+\\-\\=\\&\\|\\!\\(\\)\\{\\}\\[\\]\\^\\\"\\~\\*\\<\\>\\?\\:\\\\\\/]/',
        addslashes('\\$0'),
        $query
    );
}

Found here: https://stackoverflow.com/a/33846134

I'll add this feature in 8.0.0 version.

Please add this feature :-)

Just a quick note. In PHP You must pass or define string variable with single quotes, otherwise it will be decoded incorrectly for e.g. backslashes (obviously).

instead of

 $query = "windows\system";

must be

 $query = 'windows\system';

escapeElasticReservedChars($query);
Was this page helpful?
0 / 5 - 0 ratings