我使用elasticsearch 7.x版本,并创建了一个账号索引,其映射如下。
curl --location --request PUT 'http://localhost:9200/accounts' \
--header 'Content-Type: application/json' \
--data-raw '{
"mappings": {
"properties": {
"type": {"type": "keyword"},
"id": {"type": "keyword"},
"label": {"type": "keyword"},
"lifestate": {"type": "keyword"},
"name": {"type": "keyword"},
"users": {"type": "text"}
}
}
}'
我将用户存储为一个数组。在我的使用案例中,一个账户可以有n个用户。所以我用以下格式存储它。
curl --location --request PUT 'http://localhost:9200/accounts/_doc/account3' \
--header 'Content-Type: application/json' \
--data-raw '{
"id" : "account_uuid",
"name" : "Account_Description",
"users" : [
"id:6de57db5-8fdb-4a39-ab46-21af623692ea~~status:ACTIVE",
"id:9611e2be-784f-4a07-b5de-564b3820a660~~status:INACTIVE"
]
}'
为了根据用户ID和它的状态进行搜索,我创建了一个模式分析器,它通过~~符号进行分割,如下图。
curl --location --request PUT 'http://localhost:9200/accounts/_settings' \
--header 'Content-Type: application/json' \
--data-raw '{
"settings": {
"analysis": {
"analyzer": {
"p_analyzer": {
"type": "pattern",
"pattern" :"~~"
}
}
}
}
}'
而搜索查询调用是
curl --location --request GET 'http://localhost:9200/accounts/_search' \
--header 'Content-Type: application/json' \
--data-raw '{
"query": {
"bool": {
"filter": [
{ "term": {"id": "account_uuid"} },
{ "match" : {"users" : {
"query" : "id:<user_id>",
"analyzer" : "p_analyzer"
}}}
]
}
}
}'
如果userid格式是纯字符串,这个方法确实有效。也就是说,如果用户id存储在非UUID格式,它的工作原理很好。但对于UUID格式的id,它就不工作了。如何让它工作?
修改你的分析器以包括 -
hypen应该可以解决你的问题,因为它为UUID创建了token。
{
"settings": {
"analysis": {
"analyzer": {
"p_analyzer": {
"type": "pattern",
"pattern": "~~|-", --> note hypen is included `-`
"lowercase": true
}
}
}
}
}
使用上面的分析器可以生成以下的token。
POST your-index_analyze
{
"text" : "6de57db5-8fdb-4a39-ab46-21af623692ea~~status:ACTIVE",
"analyzer" : "my_email_analyzer"
}
生成的代币
{
"tokens": [
{
"token": "6de57db5",
"start_offset": 0,
"end_offset": 8,
"type": "word",
"position": 0
},
{
"token": "8fdb",
"start_offset": 9,
"end_offset": 13,
"type": "word",
"position": 1
},
{
"token": "4a39",
"start_offset": 14,
"end_offset": 18,
"type": "word",
"position": 2
},
{
"token": "ab46",
"start_offset": 19,
"end_offset": 23,
"type": "word",
"position": 3
},
{
"token": "21af623692ea",
"start_offset": 24,
"end_offset": 36,
"type": "word",
"position": 4
},
{
"token": "status:active",
"start_offset": 38,
"end_offset": 51,
"type": "word",
"position": 5
}
]
}
现在搜索 6de57db5-8fdb-4a39-ab46-21af623692ea
将其打成 6de57db5
, 8fdb
, 4a39
以此类推,将匹配在索引时生成的标记,并在搜索结果中出现。