如何在结果中返回特定字段的标记
例如,一个 GET 请求
curl -XGET 'http://localhost:9200/twitter/tweet/1'
返回
{
"_index" : "twitter",
"_type" : "tweet",
"_id" : "1",
"_source" : {
"user" : "kimchy",
"postDate" : "2009-11-15T14:12:12",
"message" : "trying out Elastic Search"
}
}
我希望将“_source.message”字段的标记包含在结果中
最佳答案
还有另一种方法可以使用以下 script_fields 脚本:
curl -H 'Content-Type: application/json' -XPOST 'http://localhost:9200/test-idx/_search?pretty=true' -d '{
"query" : {
"match_all" : { }
},
"script_fields": {
"terms" : {
"script": "doc[field].values",
"params": {
"field": "message"
}
}
}
}'
请务必注意,虽然此脚本返回已编入索引的实际术语,但它还会缓存所有字段值,并且在大索引上可能会使用大量内存。因此,在大型索引上,从存储的字段或源中检索字段值并使用以下 MVEL 脚本即时重新解析它们可能更有用:
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import java.io.StringReader;
// Cache analyzer for further use
cachedAnalyzer=(isdef cachedAnalyzer)?cachedAnalyzer:doc.mapperService().documentMapper(doc._type.value).mappers().indexAnalyzer();
terms=[];
// Get value from Fields Lookup
//val=_fields[field].values;
// Get value from Source Lookup
val=_source[field];
if(val != null) {
tokenStream=cachedAnalyzer.tokenStream(field, new StringReader(val));
CharTermAttribute termAttribute = tokenStream.addAttribute(CharTermAttribute);
while(tokenStream.incrementToken()) {
terms.add(termAttribute.toString())
};
tokenStream.close();
}
terms
此 MVEL 脚本可以存储为 config/scripts/analyze.mvel
并与以下查询一起使用:
curl 'http://localhost:9200/test-idx/_search?pretty=true' -d '{
"query" : {
"match_all" : { }
},
"script_fields": {
"terms" : {
"script": "analyze",
"params": {
"field": "message"
}
}
}
}'
关于java - elasticsearch - 返回字段的标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13178550/