弹性搜索:如何提取与查询短语/字符串匹配的所有“字段名称”

时间:2019-03-27 09:01:13

标签: c# elasticsearch lucene nest

我想提取在弹性搜索(存储的)索引文档中搜索文本出现的字段名称。

在弹性搜索中是否可以进行这种查询,我在C#中使用Nest Client

请参考以下示例:

示例:员工文档 { “ first_name”:“ emp first”, “ last_name”:“ emp last” }

输入搜索文字:“第一” 预期结果:[“ first_name”]

输入搜索文本:“ emp” 预期的输出:[“ first_name”,“ last_name”]

谢谢, 在

1 个答案:

答案 0 :(得分:1)

elasticsearch "Named Queries"中有一个功能,您可以命名每个查询,elasticsearch将返回匹配的查询名称

对于您的情况,您可以使用此查询

GET index/doc_type/_search
{
  "_source": [
    "first_name",
    "last_name"
  ],
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "first_name": {
              "query": "emp",
              "_name": "first_name"
            }
          }
        },
        {
          "match": {
            "last_name": {
              "query": "emp",
              "_name": "last_name"
            }
          }
        }
      ]
    }
  }
}

Elasticsearch将返回这样的结果

{
  "took": 90,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 1,
    "max_score": 16.399673,
    "hits": [
      {
        "_index": "index",
        "_type": "doc_type",
        "_id": "1",
        "_score": 16.399673,
        "_routing": "1",
        "_source": {
          "first_name": "emp first",
          "last_name": "emp last"
        },
        "matched_queries": [
          "first_name",
          "last_name"
        ]
      }
    ]
  }
}

您也可以使用highlighting

做同样的事情
GET index/doc_type/_search
{
  "_source": [
    "first_name",
    "last_name"
  ],
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "first_name": "emp"
          }
        },
        {
          "match": {
            "last_name": "emp"
          }
        }
      ]
    }
  },
  "highlight": {
    "fields": {
      "first_name": {},
      "last_name" : {}
    }
  }
}

样本响应:

{
  "took": 90,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 1,
    "max_score": 16.399673,
    "hits": [
      {
        "_index": "index",
        "_type": "doc_type",
        "_id": "1",
        "_score": 16.399673,
        "_routing": "1",
        "_source": {
          "first_name": "emp first",
          "last_name": "emp last"
        },
        "highlight": [
          "first_name" : ["<em>emp</em> first"],
          "last_name" : ["<em>emp</em> last"]
        ]
      }
    ]
  }
}