最近在做一个查询系统,用到了ES,版本是6.1。
场景:通过用户姓名搜索用户列表,名字必须完全匹配。如 输入 “贾跃” 不会检索出”贾跃亭“,输入 ”马云“ 不会检索出马云云。
6.0之前的操作:
PUT /<index_name>/_mapping
{
<type_name>: {
properties: {
<column_name>: {type: string, index: not_analyzed}
}
}
}
6.0之后:
指定type为keyword就可以了
PUT /<index_name>
{
analysis: {
analyzer: {
default: {
type: keyword
}
}
}
}
java代码
if (!ElasticsearchUtils.isIndexExist(index)) {
IndicesAdminClient indices = client.admin().indices();
CreateIndexRequestBuilder createIndexRequestBuilder = indices.prepareCreate(index);
createIndexRequestBuilder.setSettings(createSetting());
// 执行创建index请求
createIndexRequestBuilder.execute().actionGet();
XContentBuilder mapping = null;
PutMappingRequest mappingRequest=null;
try {
if (!CollectionUtils.isEmpty(fieldTypes) ) {
mapping = XContentFactory.jsonBuilder();
mapping.startObject().startObject("properties");
for (FieldTypeBean x:fieldTypes) {
//getField 拿到需要设置的字段名 getType 指定的类型keyword
mapping.startObject(x.getField()).field("type", x.getType()).endObject();
}
mapping.endObject().endObject();
mappingRequest.source(mapping);
}
} catch (IOException e) {
e.printStackTrace();
return "error";
}
indices.putMapping(mappingRequest).actionGet();
}