ElasticSearch结果数据格式

qjp7pelc  于 2022-12-22  发布在  ElasticSearch
关注(0)|答案(1)|浏览(178)

我知道有ElasticSearch管道处理器可以进行数据转换,但这是在索引文档之前。搜索结果之后是否也有类似的事情?我的用例是,我有一个文档,其中一些字段包含很长的文本,我只是想把那些长文本截短,但是我不想在索引文档之前这样做,因为那些被截短的文本是不可搜索的。我当然可以在ElasticSearch返回结果后在我的Angular UI代码上这样做。但是我想看看在返回Angular之前,是否有替代的方法让ElasticSearch引擎为我做这件事。
任何小费都很感谢。

zaq34kh6

zaq34kh61#

您可以使用脚本字段来完成此操作。首先,让我们创建一个示例文档

POST sample-index/_doc
{
  "id": 1,
  "text": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged."
}

现在,让我们使用脚本字段执行查询:

GET sample-index/_search
{
  "_source": ["id"], 
  "query": {
    "match": {
      "text": "ipsum"
    }
  },
  "script_fields": {
    "text_summary": {
      "script": "if (params['_source']['text'].length() > 40) { return params['_source']['text'].substring(0,40) + '...'; } else { return  params['_source']['text']; }"
    }
  }
}

结果会是这样的:

{
  "took": 15,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 1,
      "relation": "eq"
    },
    "max_score": 0.39556286,
    "hits": [
      {
        "_index": "sample-index",
        "_id": "ZAhIEoUBNMHtGSRnO4bt",
        "_score": 0.39556286,
        "_ignored": [
          "text.keyword"
        ],
        "_source": {
          "id": 1
        },
        "fields": {
          "text_summary": [
            "Lorem Ipsum is simply dummy text of the ..."
          ]
        }
      }
    ]
  }
}

相关问题