Grafana对接Elasticsearch数据源模板变量查询构建失败求助
Hey Reddy, let's break down why you're hitting that Template variables could not be initialized: Unexpected token “ in JSON at position 1 error, and how to fix it quickly.
The root cause here is a simple JSON syntax mistake: you're using Chinese double quotes (“ and ”) in your query string, but JSON strictly requires English half-width double quotes ("). Those curly Chinese quotes throw off the parser right at the first character, hence the position 1 error.
Correct Query to Use
Replace your current query with this properly formatted JSON (all quotes are English half-width):
{"find": "terms", "field": "sourceEnvironment"}
Extra Checks to Ensure It Works
- Verify Field Mapping: Make sure your
sourceEnvironmentfield in Elasticsearch is mapped as akeywordtype (or another aggregatable type likeconstant_keyword). If it's set totext, thetermsquery won't return valid results—you'll need to either add akeywordsub-field to the mapping or adjust the field type directly. - Validate in Kibana First: To confirm the field is working as expected, run a quick aggregation query in Kibana's Dev Tools:
GET /your_target_index/_search { "size": 0, "aggs": { "unique_envs": { "terms": { "field": "sourceEnvironment", "size": 100 } } } }
If this returns a list of your sourceEnvironment values, you know the field is ready to use in Grafana. Just plug the corrected JSON query into your template variable setup, and it should initialize without errors.
内容的提问来源于stack exchange,提问作者Reddy SK

