### Elasticsearch Version

8.8.0-SNAPSHOT

### Installed Plugins

_No response_

### Java Version

_bundled_

### OS Version

MacOS

### Problem Description

API when called is returning invalid response, on the same data terms aggs query runs fine 

![image](https://user-images.githubusercontent.com/3505601/220749805-ddf0d735-60d5-4e45-85bf-941ea3076a3f.png)


When run as aggs query 

![image](https://user-images.githubusercontent.com/3505601/220764360-49f7b648-8b15-43cf-afe2-01bd62e8ebc5.png)


### Steps to Reproduce

Queries are mentioned above ^^

### Logs (if relevant)

_No response_
server/src/main/java/org/elasticsearch/index/mapper/flattened/FlattenedFieldMapper.java
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.xcontent.XContentParser;
import java.io.IOException;
import java.util.Map;
/**
 * A field mapper that accepts a JSON object and flattens it into a single field. This data type
 * can be a useful alternative to an 'object' mapping when the object has a large, unknown set
 * of keys.
 *
 * Currently the mapper extracts all leaf values of the JSON object, converts them to their text
 * representations, and indexes each one as a keyword. It creates both a 'keyed' version of the token
 * to allow searches on particular key-value pairs, as well as a 'root' token without the key
 *
 * As an example, given a flattened field called 'field' and the following input
 *
 * {
 *   "field": {
 *     "key1": "some value",
 *     "key2": {
 *       "key3": true
 *     }
 *   }
 * }
 *
 * the mapper will produce untokenized string fields with the name "field" and values
 * "some value" and "true", as well as string fields called "field._keyed" with values
 * "key\0some value" and "key2.key3\0true". Note that \0 is used as a reserved separator
 *  character (see {@link FlattenedFieldParser#SEPARATOR}).
 */
public final class FlattenedFieldMapper extends FieldMapper {