如何在ElasticSearch中获取包含10个及以上字段的文档?
Alright, let's sort this out for you. The query you tried won't work because Elasticsearch doesn't expose a built-in fields field you can target with a range filter. We need to use a script to dynamically calculate the number of fields per document instead.
Correct Query to Retrieve Documents with 10+ Fields
Option 1: Count Indexed Fields
If you only care about fields that are indexed (the ones Elasticsearch can search against), use this query:
{ "query": { "script": { "script": { "source": "doc.size() >= 10", "lang": "painless" } } } }
doc.size()returns the count of indexed fields in the document. This is faster than checking the full source, as it uses indexed metadata.
Option 2: Count All Fields (Including Non-Indexed Source Fields)
If you want to count every field present in the document's _source (even fields that aren't indexed), use this variation:
{ "query": { "script": { "script": { "source": "params._source.size() >= 10", "lang": "painless" } } } }
Key Notes
- Script queries run logic against every document, so they can be slower on large datasets. If you need to run this often, consider precomputing the field count at index time (add a
field_countfield when you index documents) or using a runtime field for better performance. - Ensure your Elasticsearch cluster allows script queries (they're enabled by default, but some restricted environments might disable them).
内容的提问来源于stack exchange,提问作者cmac
相关产品推荐
相关产品推荐

