ElasticSearch 6.1无法遍历unavailability数组字段的问题求助
Hey there, let's break down why you're hitting this error and walk through actionable fixes:
1. The core issue: unavailability is likely a nested field
From your mapping and data structure, unavailability is an array of objects—Elasticsearch typically stores this as a nested type. Nested fields split each object in the array into separate hidden documents, which means you can't directly access the full array using the doc object in your script. The doc context only works with flat, non-nested field values.
Quick fix: Use params._source instead of doc
Modify your script to pull the raw array from the document's source data instead. This preserves the original array structure you need to iterate over. Here's how to adjust your script:
def unavailabilities = params._source.unavailability; for (def entry : unavailabilities) { // Your existing logic here (use entry.starts_at, entry.ends_at, etc.) }
This works because params._source gives you direct access to the raw document data as it was indexed.
2. Double-check field spelling and mapping presence
Make sure:
- The field name in your script matches exactly what's in the mapping (it's case-sensitive! Confirm it's
unavailability, notUnavailabilityor a misspelled variant). - The
aircrafttype in your index actually includes theunavailabilityfield. Cross-reference your mapping snippet to ensure the field is listed under theaircrafttype's properties.
3. Confirm _source is enabled
Elasticsearch lets you disable _source (the raw document storage) for smaller index sizes, but if your data includes the unavailability array, it's probably enabled. To verify, run this command against your index:
GET /your_index_name/_settings
Look for "_source": {"enabled": true} in the response. If it's disabled, you'll need to reindex your data with _source enabled to use the params._source approach.
4. Alternative: Use nested queries for per-object logic
If you need to run checks against individual unavailability objects (instead of the entire array), restructure your query to use a nested clause. This puts the script in the context of each nested object, letting you access fields via doc:
{ "query": { "nested": { "path": "unavailability", "query": { "script": { "script": { "source": "doc['unavailability.starts_at'].value ...", "lang": "painless" } } } } } }
This is ideal if you're filtering or scoring documents based on specific entries in the unavailability array.
内容的提问来源于stack exchange,提问作者Hudson Dunice

