我使用elasticsearch来索引我的文档。

是否有可能指示它只返回特定的字段,而不是它所存储的整个json文档?


当前回答

有几种方法可以用于实现特定领域的结果。 可以通过源方法。 根据我们的兴趣,另一个方法filter_path也可以用来接收更清晰、更概括的答案:

索引"index1"中的文档Json:

"hits" : [
  {
    "_index" : "index1",
    "_type" : "_doc",
    "_id" : "1",
    "_score" : 1,
    "_source" : {
      "year" : 2020,
      "created_at" : "2020-01-29",
      "url" : "www.github.com/mbarr0987",
      "name":"github"
    }
  }

查询:

GET index1/_search?filter_path=hits.hits._source.url
{
  "query": { 
        {"term": {"name":"github" }
    }
  }
}

输出:

{
  "hits" : {
    "hits" : [
      {
        "_source" : {
          "url" : "www.github.com/mbarr0987"
            }
          }
      ]
   }
}

其他回答

是的,通过使用源过滤器你可以做到这一点,这里是文档源过滤器

示例请求

POST index_name/_search
 {
   "_source":["field1","filed2".....] 
 }

输出将是

{
  "took": 57,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 1,
    "max_score": 1,
    "hits": [
      {
        "_index": "index_name",
        "_type": "index1",
        "_id": "1",
        "_score": 1,
        "_source": {
          "field1": "a",
          "field2": "b"
        },
        {
          "field1": "c",
          "field2": "d"
        },....
      }
    ]
  }
}

在这里,你可以在输出中指定你想要的字段,也可以指定你不想要的字段:

  POST index_name/_search
    {
        "_source": {
            "includes": [ "field_name", "field_name" ],
            "excludes": [ "field_name" ]
        },
        "query" : {
            "match" : { "field_name" : "value" }
        }
    }

例如,你有一个有三个字段的doc:

PUT movie/_doc/1
{
  "name":"The Lion King",
  "language":"English",
  "score":"9.3"
}

如果你想返回名字和分数,你可以使用下面的命令:

GET movie/_doc/1?_source_includes=name,score

如果你想获得一些匹配模式的字段:

GET movie/_doc/1?_source_includes=*re

可能会排除一些字段:

GET movie/_doc/1?_source_excludes=score

这是另一个解决方案,现在使用匹配表达式

源过滤允许控制每次命中_source字段返回的方式。

使用Elastiscsearch 5.5版进行测试

关键字includes定义了具体字段。

GET /my_indice/my_indice_type/_search
{
  "_source": {
    "includes": [
      "my_especific_field"
    ]
  },
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "_id": "%my_id_here_without_percent%"
          }
        }
      ]
    }
  }
}

有几种方法可以用于实现特定领域的结果。 可以通过源方法。 根据我们的兴趣,另一个方法filter_path也可以用来接收更清晰、更概括的答案:

索引"index1"中的文档Json:

"hits" : [
  {
    "_index" : "index1",
    "_type" : "_doc",
    "_id" : "1",
    "_score" : 1,
    "_source" : {
      "year" : 2020,
      "created_at" : "2020-01-29",
      "url" : "www.github.com/mbarr0987",
      "name":"github"
    }
  }

查询:

GET index1/_search?filter_path=hits.hits._source.url
{
  "query": { 
        {"term": {"name":"github" }
    }
  }
}

输出:

{
  "hits" : {
    "hits" : [
      {
        "_source" : {
          "url" : "www.github.com/mbarr0987"
            }
          }
      ]
   }
}