17

Is it possible to put a comment into an Elasticsearch query JSON? I want to be able to add some extra text to the query that's human-readable but ignored by Elasticsearch.

For example, if I have the following query:

{ "query": { "match_all": {} } }

I would like to be able to add a comment, maybe something like this:

{ "query": { "match_all": {} }, "comment": "This query matches all documents." }

Hacky workarounds (e.g., a query clause that has no effect on the results) would also be appreciated.

Nate Sullivan
  • 303
  • 3
  • 8
  • Interesting question but I was wondering what could be the use of it? If you are using Java, you could wrap a QueryBuilder object and a String in a separate object. – Animesh Pandey Mar 16 '17 at 20:43
  • You can add such a field to a mapping but may be not a query!. ? Ref: https://www.elastic.co/guide/en/elasticsearch/reference/current/enabled.html – Animesh Pandey Mar 16 '17 at 20:49
  • 2
    @AnimeshPandey I'd like to annotate each query with some info about where in my application the query comes from. That way, when I'm looking through the slowlog, it's easy to figure out where the slow queries are coming from. I was inspired by [the Marginalia Ruby gem](https://github.com/basecamp/marginalia), which implements similar behavior for SQL queries. – Nate Sullivan Mar 16 '17 at 21:23

3 Answers3

10

Seems like Elasticsearch does allow Javascript comments (/* */ and //) in JSON (Despite the JSON standard not supporting comments). So that's another option.

nimrodm
  • 23,081
  • 7
  • 58
  • 59
  • I use this to document queries and mappings in my application sources, so this approach is helpful – gimix Aug 06 '19 at 08:10
  • While this works, be aware that it is not an explicit feature. So you should not build production functionality on this. To quote this [2017 answer from an elasticsearch developer](https://discuss.elastic.co/t/can-i-use-comments-in-json-request-to-es/100312): _I would not assume that Elasticsearch allows comments inside JSON requests. As you mentioned, the JSON spec does not allow comments and I am surprised that it worked in your test to be honest. Its not something that is tested and not something we explicitly support so it could stop working at any time._ – buddemat Apr 05 '22 at 08:42
6

One solution to make this work is to use named queries, i.e. each query can be named

{
  "query": {
    "match_all": {
      "_name": "This query matches all documents."
    }
  }
}
Val
  • 207,596
  • 13
  • 358
  • 360
3

by inserting # [hash symbol] ,yes you can put comment for elastic search queries in console

ganivk
  • 31
  • 1