世界上并没有完美的程序,但是我们并不因此而沮丧,因为写程序就是一个不断追求完美的过程。
-侯氏工坊
功能
- 返回匹配文本、数字、日期和布尔值的文档
- 在匹配之前会对文本进行分析
- match查询是全文搜索的标准查询
- match包括模糊匹配
关键字
- match
- <field
- query
- 要匹配的文本、数字、日期或布尔值
- analyzer
- 分析器,首先将query中的内容通过分析器进行分析,将分析的结果做为查询
- 如果没有指定,默认使用索引时的分析器
- auto_generate_synonyms_phrase_query
- 自动生成同义短语搜索
- 默认为true
- fuzziness
- 模糊搜索允许的最大编辑距离
- max_expansions
- 查询可扩展的最大词项数
- 默认50
- prefix_length
- 模糊匹配前缀不变值
- 默认0
- fuzzy_transpositions
- 模糊匹配是否允许相邻字符交换
- 默认true
- fuzzy_rewrite
- 重写查询的方法
- 如果fuzziness不为0,默认的方法为top_terms_blended_freqs_${max_expansions}
- lenient
- 宽容度
- 如果为true,不合适的查询文本会被忽略掉
- 默认为false
- operator
- 用于解释文本的布尔逻辑
- OR
- 任意匹配
- AND
- 全部匹配
- minimum_should_match
- 文档所匹配的最小子句数
- zero_terms_query
- 如果经过分析器后的词项为0,是否返回文档
- none
- 不返回文档
- 默认
- all
- 返回所有文档
- query
- <field
原语句
DELETE index_match
PUT index_match
{
"mappings": {
"properties": {
"content": {"type": "text"}
}
}
}
GET index_match/_mapping
POST index_match/_doc/1
{
"content": "my favorite food is cold porridge"
}
POST index_match/_doc/2
{
"content": "when it's cold my favorite food is porridge"
}
POST index_match/_doc/3
{
"content": "my favorite food is hot water"
}
POST index_match/_doc/4
{
"content": "my favorite food is hello good me"
}
GET /index_match/_search
{
"query": {
"match": {
"content": "hello food"
}
}
}
GET /index_match/_search
{
"query": {
"match": {
"content": {
"query": "hello food",
"operator": "and"
}
}
}
}
java实现
- 实体
@Data
@EsIndex(index = "index_match")
public class MatchEntity {
private String content;
}
- 接口
public interface MatchService {
/**
* 匹配
* @return
* @throws Exception
*/
SearchResponse<Object> match()
throws Exception;
}
- 实现
@Service
public class MatchServiceImpl
implements MatchService {
@Resource
private ElasticsearchClient elasticsearchClient;
@Override
public SearchResponse<Object> match()
throws Exception {
return elasticsearchClient.search(search -> search
.source(MatchUtils.sourceConfig())
.index(getIndex())
.fields(getField())
.query(getMatchQuery()),
Object.class);
}
// -------------------------------------------------------------------------
private String getIndex() {
return EsAnnotationUtils.getIndex(MatchEntity.class);
}
private FieldAndFormat getField() {
return MatchUtils.field(fieldStr());
}
private Query getMatchQuery() {
return MatchUtils.matchQuery(
fieldStr(),
FieldValue.of("hello food"),
"match",
Operator.And);
}
private String fieldStr() {
return EsAnnotationUtils.getField(MatchEntity::getContent);
}
}
- 工具
public class MatchUtils {
private MatchUtils() {}
public static SourceConfig sourceConfig() {
return SourceConfig.of(source -> source.fetch(false));
}
public static FieldAndFormat field(
String field) {
return FieldAndFormat.of(fieldAndFormat -> fieldAndFormat
.field(field));
}
public static Query matchQuery(
String field,
FieldValue query,
String queryName,
Operator operator) {
return Query.of(q -> q
.match(match -> match
.field(field)
.query(query)
.queryName(queryName)
.operator(operator)));
}
}