更新时间:2023-09-18 13:29:28
您需要 1.使用设置创建索引
PUT joinword
{
"settings": {
"analysis": {
"filter": {
"word_joiner": {
"type": "shingle",
"output_unigrams": "true",
"token_separator": ""
}
},
"analyzer": {
"word_join_analyzer": {
"type": "custom",
"tokenizer": "standard",
"filter": [
"lowercase",
"word_joiner"
]
}
}
}
}
}
2.检查分析仪是否按预期工作
GET joinword/_analyze?pretty
{
"analyzer": "word_join_analyzer",
"text": "ONE TWO"
}
输出:
{
"tokens" : [ {
"token" : "one",
"start_offset" : 0,
"end_offset" : 3,
"type" : "<ALPHANUM>",
"position" : 0
}, {
"token" : "onetwo",
"start_offset" : 0,
"end_offset" : 7,
"type" : "shingle",
"position" : 0
}, {
"token" : "two",
"start_offset" : 4,
"end_offset" : 7,
"type" : "<ALPHANUM>",
"position" : 1
} ]
}
因此,现在您可以按 one
, two
或 onetwo
查找该文档.搜索将不区分大小写.
So now you can find this document by one
, two
or onetwo
. A search will be case insensitive.
完整项目可在GitHub上获得.
实体:
@Document(indexName = "document", type = "document", createIndex = false)
@Setting(settingPath = "elasticsearch/document_index_settings.json")
public class DocumentES {
@Id()
private String id;
@Field(type = String, analyzer = "word_join_analyzer")
private String title;
public DocumentES() {
}
public DocumentES(java.lang.String title) {
this.title = title;
}
public java.lang.String getId() {
return id;
}
public void setId(java.lang.String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public java.lang.String toString() {
return "DocumentES{" +
"id='" + id + '\'' +
", title='" + title + '\'' +
'}';
}
}
主要
@SpringBootApplication
@EnableConfigurationProperties(value = {ElasticsearchProperties.class})
public class Application implements CommandLineRunner {
@Autowired
ElasticsearchTemplate elasticsearchTemplate;
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
@Override
public void run(String... args) throws Exception {
elasticsearchTemplate.createIndex(DocumentES.class);
elasticsearchTemplate.putMapping(DocumentES.class);
elasticsearchTemplate.index(new IndexQueryBuilder()
.withIndexName("document")
.withType("document")
.withObject(new DocumentES("ONE TWO")).build()
);
Thread.sleep(2000);
NativeSearchQuery query = new NativeSearchQueryBuilder()
.withIndices("document")
.withTypes("document")
.withQuery(matchQuery("title", "ONEtWO"))
.build();
List<DocumentES> result = elasticsearchTemplate.queryForList(query, DocumentES.class);
result.forEach (System.out::println);
}
}