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

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


当前回答

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

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

其他回答

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

在Elasticsearch 5。X上述方法是不赞成的。 你可以使用_source方法,但是在某些情况下,存储一个字段是有意义的。例如,如果你有一个带有标题、日期和一个非常大的内容字段的文档,你可能只想检索标题和日期,而不必从一个大的_source字段中提取这些字段:

在这种情况下,你可以使用:

{  
   "size": $INT_NUM_OF_DOCS_TO_RETURN,
   "stored_fields":[  
      "doc.headline",
      "doc.text",
      "doc.timestamp_utc"
   ],
   "query":{  
      "bool":{  
         "must":{  
            "term":{  
               "doc.topic":"news_on_things"
            }
         },
         "filter":{  
            "range":{  
               "doc.timestamp_utc":{  
                  "gte":1451606400000,
                  "lt":1483228800000,
                  "format":"epoch_millis"
               }
            }
         }
      }
   },
   "aggs":{  

   }
}

有关如何为存储的字段建立索引,请参阅文档。 总是很高兴得到好评!

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

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

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

源过滤允许控制每次命中_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%"
          }
        }
      ]
    }
  }
}