如何在ElasticSearch中搜索特定单词和精确匹配

jvlzgdj9  于 2022-09-20  发布在  ElasticSearch
关注(0)|答案(1)|浏览(215)

标题示例数据

actiontype test
booleanTest
test-demo
test_demo
Test new account object
sync accounts data test

标题的默认Map

"title": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
 },

已尝试此查询搜索

{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "title": "test"
          }
        }
      ]
    }
  },
}

这是我的期待

对于特定的单词(例如:测试),它应该返回以下标题

expect
        actiontype test
        booleanTest
        test-demo
        test_demo
        Test new account object
        sync accounts data test

但是

got
            actiontype test
            test-demo
            test_demo
            Test new account object
            sync accounts data test

对于完全匹配(例如:同步帐户数据测试),它应该只返回this(sync accounts data test),但获得了包含this单词(sync,account,data,test)的所有记录。

我该怎么做才能做到这一点呢?谢谢。

2j4z5cfb

2j4z5cfb1#

我不确定您使用的是哪个ES版本,但下面的内容应该会让您有所了解。

1.使用您的Map,您可以获得具有test的所有标题文本,包括使用query string查询类型的booleanTest。例.

GET {index-name}/{mapping}/_search
{
  "query": {
    "query_string": {
      "default_field": "title",
      "query": "*test*"
    }
  }
}

但是,要使其正常工作,请确保您为title字段提供了一个带有lowercase分析器过滤器的分析器(请参阅下面的设置示例)。您当前的Map将不起作用,因为它只是按原样纯text...默认情况下为test /= TEST

1.还有其他方法,如果你有兴趣了解ES的工作原理……例.您还可以通过将自定义nGram``filter写入索引设置来匹配match查询中的booleanTest。就像这样,

{
  "index": {
    "settings": {
      "index": {
        "analysis": {
          "filter": {
            "nGram": {
              "type": "nGram",
              "min_gram": "2",
              "max_gram": "20"
            }
          },
          "ngram_analyzer": {
            "filter": [
              "lowercase",
              "nGram"
            ],
            "type": "custom",
            "tokenizer": "standard"
          }
        }
      }
    }
  }
}

注:ngram_analyzer只是一个名字。你可以随便叫它什么。min_grammax_gram:选择适合您的数字。

了解更多关于n元语法过滤器的信息,商品和劣质在这里:N-GRAM

然后,您可以将分析器添加到您的字段Map中,

{
  "title": {
    "type": "text",
    "fields": {
      "keyword": {
        "type": "keyword",
        "ignore_above": 256,
        "analyzer": "ngram_analyzer"
      }
    }
  }
}

最后,为了实现精确匹配,这些规则适用于类型keyword。因此,根据您的Map,您已经有了关键字字段,因此您可以使用term查询通过搜索title.keyword字段来获得精确匹配;

GET {index-name}/{mapping}/_search
{
  "query": {
    "term": {
      "title.keyword": {
        "value": "sync accounts data test"
      }
    }
  }
}

此外,您还需要阅读/了解有关这些解决方案的更多信息,并根据您的索引设置和需求决定最佳解决方案。此外,可能有更多的方法来实现你所需要的,这应该是一个很好的开始。

相关问题