OpenSearch [Elasticsearch]查找存在于文本中的文档

cczfrluj  于 2023-04-11  发布在  ElasticSearch
关注(0)|答案(1)|浏览(167)

我正在使用OpenSearch,我有一个包含多个练习名称的大型输入文本。我想从输入文本中提取这些练习名称,并在OpenSearch索引中搜索与这些名称匹配的文档。
输入文本可以是任何格式,并包含各种字符,如小写或大写字母、数字和特殊字符。输入文本中的练习名称不保证以大写字母开头或遵循任何特定模式。以下是输入文本的示例:

I will make a good 10 push-ups and Dumbbell Deficit Push-up

在索引中,我有:

[
    {
        "id": 2,
        "name": "Ankle Circles"
    },
    {
        "id": 3,
        "name": "Barbell Deep Squat"
    },
    {
        "id": 10,
        "name": "Push-ups"
    },
    {
        "id": 11,
        "name": "Sit-up"
    },
    {
        "id": 12,
        "name": "Air Squats"
    },
    {
        "id": 13,
        "name": "Dumbbell Deficit Push-up"
    },
    {
        "id": 14,
        "name": "Pretzel Stretch"
    },
    {
        "id": 15,
        "name": "Cobra Stretch"
    },
    {
        "id": 20,
        "name": "Push-ups with Elevated Feet"
    }...
]

这里是我的搜索请求:

SearchResponse<ExerciseOSDto> searchResponse = openSearchClient.search(
        s -> s.index("exercises")
            .query(new Query.Builder().match(
                    new MatchQuery.Builder()
                        .field("name")
                        .query(new FieldValue.Builder()
                            .stringValue(payload.getText()).build())
                        .operator(Operator.Or) 
                        .build())
                .build()), ExerciseOSDto.class);

但是从这个例子中,我有所有的练习(向上/向上/推)。
从输入文本中,我想得到id为-1013的练习
从输入文本中提取这些练习名称并在OpenSearch中执行搜索的最佳方法是什么?
任何帮助或指导将不胜感激!

j1dl9f46

j1dl9f461#

你可以用customize the analyzer来达到这个目的
这里我使用基本的tokenizertoken filter创建了一个分析器

PUT exercises
{
  "settings": {
    "analysis": {
      "analyzer": {
        "exercise_analyzer": {
          "tokenizer": "whitespace",
          "filter": ["lowercase"]
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "name": {
        "type": "text",
        "analyzer": "exercise_analyzer"
      }
    }
  }
}

插入数据后,可以执行匹配查询(与您提供的代码逻辑相同)

GET exercises/_search
{
  "query": {
    "match": {
      "name": "I will make a good 10 push-ups and Dumbbell Deficit Push-up"
    }
  }
}

但是需要指出的是,按照这种方式,你仍然会匹配到一些不完全是你想要的文档。例如,在这种情况下,Push-ups with Elevated Feet
如果仅仅依靠Elasticsearch/Opensearch上的全文搜索是很难实现的。
我觉得最简单的方法是在Elasticsearch/Opensearch得到搜索结果后,在客户端应用额外的过滤逻辑

# input_str represent the input text
# results represent the exercises name you got from opensearch
final_results = [r for r in results if lower(r) in lower(input_str)]

让我知道如果我错过了你的观点,或任何你认为它不是工作。谢谢!

相关问题