精简Elasticsearch查询返回结果(只返回指定字段)

有时候我们可能并不想返回所有的字段,甚至连元数据字段需要的都很少,所以我们想精简返回的结果。

方法所有的API都接受一个filter_path参数,这个参数支持逗号分隔,可以同时填写多个值。
例如,如果只想要返回查询的时间、事件的id和分值,可以像下面这样:

curl -XGET 'localhost:9200/_search?pretty&filter_path=took,hits.hits._id,hits.hits._score'
{
  "took" : 3,
  "hits" : {
    "hits" : [
      {
        "_id" : "3640",
        "_score" : 1.0
      },
      {
        "_id" : "3642",
        "_score" : 1.0
      }
    ]
  }
}

也支持通配符*来忽略对某个字段的过滤:

curl -XGET 'localhost:9200/_nodes/stats?filter_path=nodes.*.ho*'
{
  "nodes" : {
    "lvJHed8uQQu4brS-SXKsNA" : {
      "host" : "portable"
    }
  }
}

使用**则会忽略最大长度的路径,与Spring MVC的Url匹配差不多。

curl 'localhost:9200/_segments?pretty&filter_path=indices.**.version'
{
  "indices" : {
    "movies" : {
      "shards" : {
        "0" : [ {
          "segments" : {
            "_0" : {
              "version" : "5.2.0"
            }
          }
        } ],
        "2" : [ {
          "segments" : {
            "_0" : {
              "version" : "5.2.0"
            }
          }
        } ]
      }
    },
    "books" : {
      "shards" : {
        "0" : [ {
          "segments" : {
            "_0" : {
              "version" : "5.2.0"
            }
          }
        } ]
      }
    }
  }
}

注意,elasticsearch一般会直接返回一条数据的原始信息,即_source字段。如果要对_source进行过滤,可以参考下面的用法:

curl -XGET 'localhost:9200/_search?pretty&filter_path=hits.hits._source&_source=title'
{
  "hits" : {
    "hits" : [ {
      "_source":{"title":"Book #2"}
    }, {
      "_source":{"title":"Book #1"}
    }, {
      "_source":{"title":"Book #3"}
    } ]
  }
}

你可能感兴趣的:(精简Elasticsearch查询返回结果(只返回指定字段))