ElasticsearchOperations 查询不返回完全匹配
Posted
技术标签:
【中文标题】ElasticsearchOperations 查询不返回完全匹配【英文标题】:ElasticsearchOperations query not returning exact matches 【发布时间】:2021-06-28 22:42:52 【问题描述】:我正在为 Elastic 搜索中的查询而苦苦挣扎,所以我希望这里有人可以帮助我。
所以我在弹性搜索中有一个索引,它存储了用户的一些基本信息。然后我有我的 Spring Boot API,它允许客户端搜索所述索引。
在我的应用中,当用户注册时,他们可以选择网站上的显示名称。现在,当他们输入显示名称时,我希望能够检查弹性并告诉他们是否已使用。
但是,我正在苦苦挣扎的地方是,假设我的索引中有一个用户,显示名称为“John Boy”,现在用户 2 注册并想要显示名称“男孩”。当我搜索“男孩”是否被拍摄时,我会返回“约翰男孩”。我想要它,所以查询告诉我“男孩”是否有空,而不关心“约翰男孩”是否被占用。
我以为我只是对 ES 有所了解,但也许不是,我的印象是字段(请参阅下面的索引映射)关键字我可以进行术语搜索并返回完全匹配?
下面我包含了我的 Pojo 和我的 ES 索引映射。请如果有人可以帮助我....感谢阅读:
搜索方法
public long checkUserNameAvailability(String query)
QueryBuilder matchSpecificFieldQuery= QueryBuilders
.termQuery("displayName", query);
Query searchQuery = new NativeSearchQueryBuilder()
.withFilter(matchSpecificFieldQuery)
.build();
SearchHits<UserProfile> searchSuggestions =
elasticsearchOperations.search(searchQuery,
UserProfile.class,
IndexCoordinates.of(elasticUserIndex));
List<UserProfile> suggestions = new ArrayList<>();
return searchSuggestions.getTotalHits();
波乔
@Getter
@Setter
@Document(indexName = "userprofiles")
public class UserProfile
@Field(type = FieldType.Text, name = "userId")
private String userId;
@Field(type = FieldType.Keyword, name = "displayName")
private String displayName;
@Field(type = FieldType.Text, name = "name")
private String name;
ES 映射
"userprofiles":
"mappings":
"properties":
"displayName":
"fields":
"keyword":
"ignore_above": 256,
"type": "keyword"
,
"type": "text"
,
"name":
"fields":
"keyword":
"ignore_above": 256,
"type": "keyword"
,
"type": "text"
,
"userId":
"fields":
"keyword":
"ignore_above": 256,
"type": "keyword"
,
"type": "text"
旁注: 我正在使用 Spring Boot 版本 2.4.3
和
compile('org.springframework.boot:spring-boot-starter-data-elasticsearch')
compile group: 'org.springframework.data', name: 'spring-data-elasticsearch', version: '4.1.5'
再次感谢
【问题讨论】:
嗨,有趣,也许 exact match 查询而不是术语查询可能会有所帮助 【参考方案1】:也许你应该使用关键字查询,因为'displayName'字段类型是文本,它将在查询和索引中都是分析器。
QueryBuilder matchSpecificFieldQuery= QueryBuilders
.termQuery("displayName.keyword", query);
【讨论】:
非常感谢!是否可以使术语查询不区分大小写? 好的,我重新创建了索引以设置“normalizer”:“case_insensitive_normalizer”,然后执行匹配查询,它现在可以按预期工作。非常感谢您的帮助【参考方案2】:我认为您应该重新考虑您正在使用的查询类型。 尝试在 .keyword 字段上使用简单匹配。
【讨论】:
非常感谢 Matab,我真的快疯了以上是关于ElasticsearchOperations 查询不返回完全匹配的主要内容,如果未能解决你的问题,请参考以下文章