如何在elasticsearch中的嵌套字段中生成扁平子字段?

kognpnkq  于 2021-06-10  发布在  ElasticSearch
关注(0)|答案(1)|浏览(390)

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

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,  
    },  
  ]  
}

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

68bkxrlz

68bkxrlz1#

要匹配“我有一本书”,并返回匹配的时间:0,1,2。
添加索引Map、搜索查询和搜索结果的工作示例
索引Map:

{
  "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
                  }
                }
              ]
            }
          }
        }
      }

相关问题