如何在弹性搜索的嵌套字段中制作扁平子字段?

How to make flattened sub-field in the nested field in elastic search?

在这里,我有一个索引文档,例如:

doc = {  
  "id": 1,  
  "content": [  
    {  
      "txt": I,  
      "time": 0,  
    },  
    {  
      "txt": have,  
      "time": 1,  
    },  
    {  
      "txt": a book,  
      "time": 2,  
    },  
    {  
      "txt": do not match this block,  
      "time": 3,  
    },  
  ]  
}  

我想匹配“我有一本书”,return匹配时间:0,1,2。有谁知道这种情况如何建立索引和查询吗? 我认为“content.txt”应该展平,但“content.time”应该嵌套?

want to match "I have a book", and return the matched time: 0,1,2.

添加具有索引映射、搜索查询和搜索结果的工作示例

索引映射:

{
  "mappings": {
    "properties": {
      "content": {
        "type": "nested"
      }
    }
  }
}

搜索查询:

{
  "query": {
    "nested": {
      "path": "content",
      "query": {
        "bool": {
          "must": [
            {
              "match": {
                "content.txt": "I have a book"
              }
            }
          ]
        }
      },
      "inner_hits": {}
    }
  }
}

搜索结果:

"inner_hits": {
          "content": {
            "hits": {
              "total": {
                "value": 3,
                "relation": "eq"
              },
              "max_score": 2.5226097,
              "hits": [
                {
                  "_index": "64752029",
                  "_type": "_doc",
                  "_id": "1",
                  "_nested": {
                    "field": "content",
                    "offset": 2
                  },
                  "_score": 2.5226097,
                  "_source": {
                    "txt": "a book",
                    "time": 2
                  }
                },
                {
                  "_index": "64752029",
                  "_type": "_doc",
                  "_id": "1",
                  "_nested": {
                    "field": "content",
                    "offset": 0
                  },
                  "_score": 1.5580825,
                  "_source": {
                    "txt": "I",
                    "time": 0
                  }
                },
                {
                  "_index": "64752029",
                  "_type": "_doc",
                  "_id": "1",
                  "_nested": {
                    "field": "content",
                    "offset": 1
                  },
                  "_score": 1.5580825,
                  "_source": {
                    "txt": "have",
                    "time": 1
                  }
                }
              ]
            }
          }
        }
      }