我使用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"
            }
          }
      ]
   }
}

其他回答

response_filtering

所有REST api都接受一个filter_path参数 减少elasticsearch返回的响应。此参数取 用点符号表示的以逗号分隔的过滤器列表。

https://stackoverflow.com/a/35647027/844700

对于ES版本5。X及以上,你可以这样查询ES:

    GET /.../...
    {
      "_source": {
        "includes": [ "FIELD1", "FIELD2", "FIELD3" ... " ]
      },
      .
      .
      .
      .
    }

例如,你有一个有三个字段的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

在java中,你可以这样使用setFetchSource:

client.prepareSearch(index).setTypes(type)
            .setFetchSource(new String[] { "field1", "field2" }, null)

有几种方法可以用于实现特定领域的结果。 可以通过源方法。 根据我们的兴趣,另一个方法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"
            }
          }
      ]
   }
}