[英]Elastic search : How to search in two documents in single index?
我在一個名為inventory 的索引中配置了兩個文檔。
庫存索引映射屬性如下:
{
"mappings": {
"properties": {
"type": {"type": "keyword"},
"id": {"type": "keyword"},
"sourceId": {"type": "keyword"},
"targetId": {"type": "keyword"},
"firstName": {"type": "text"},
"lastName": {"type": "text"},
"createdBy": {"type": "text"},
"p_type": {"type": "text"},
"model": {"type": "text"},
"OS": {"type": "keyword"}
}
}
}
profile 有以下信息
用戶:
{ "type":"profile", "id" : "user1", "p_type" : "user", "firstName" : "Ashok", "lastName" : "S" }
{ "type":"profile", "id" : "user2", "p_type" : "user", "firstName" : "Arun", "lastName" : "V" }
手機:
{ "type":"profile", "id" : "mobile1", "p_type" : "mobile", "model" : "samsung", "OS" : "Android" }
{ "type":"profile", "id" : "mobile2", "p_type" : "mobile", "model" : "iPhone", "OS" : "iOS" }
p2p-relation有哪個用戶使用了哪個移動信息:
{ "type":"p2p-relation", "id" : "user1-owns-mobile1", "sourceId" : "user1", "targetId" : "mobile1", "createdBy" : "admin" }
{ "type":"p2p-relation", "id" : "user1-owns-mobile2", "sourceId" : "user1", "targetId" : "mobile2", "createdBy" : "admin" }
在我們的業務案例中,我們需要檢索用戶擁有的 android/iOS 手機列表,我們從客戶那里獲得輸入。
也就是說,如果 user1 請求/mymobiles?query=os==Android ,它應該將其轉換為 ES 並期待
{ “type”:“profile”,“id”:“mobile1”,“p_type”:“mobile”,“model”:“samsung”,“OS”:“Android”}
結果,如果 user2 請求相同,它應該返回空。
我試過查詢和布爾。 但它只在單個文檔中搜索。 如何在彈性搜索中實現這一點?
model以上屬於多對多關系數據model。 一個用戶可以有許多移動電話分配給他,一個移動設備可以在一段時間內分配給許多用戶。 因此將數據 model 更改為將其存儲為嵌套對象。
{
"mappings": {
"properties": {
"type": {"type": "keyword"},
"id": {"type": "keyword"},
"firstName": {"type": "text"},
"lastName": {"type": "text"},
"createdBy": {"type": "text"},
"model": {"type": "text"},
"OS": {"type": "keyword"},
"mobiles" : {
"type" : "nested",
"properties" : {
"id": {"type": "keyword"},
"model": {"type": "text"},
"OS": {"type": "keyword"},
"createdBy": {"type": "text"}
}
},
"users" : {
"type" : "nested",
"properties" : {
"id": {"type": "keyword"},
"firstName": {"type": "keyword"},
"lastName": {"type": "keyword"},
"createdBy": {"type": "text"}
}
}
}}}
但痛苦的是,每當將手機分配給用戶時,我都需要花費額外的精力來更新兩行。
數據存儲如下
{ "type":"profile", "id" : "user1", "firstName" : "Ashok", "lastName" : "S", "mobiles" : [ {"id" : "uuid1", "model": "samsung", "OS" : "Android"}] }
{ "type":"profile", {"id" : "uuid1", "model": "samsung", "OS" : "Android"}, "users" : [ "id" : "user1", "firstName" : "Ashok", "lastName" : "S"] }
為了回答 /mymobiles?query=os==Android,我使用了以下查詢。
{
"query": {
"bool": {
"must": [
{
{ "term": {"OS": "android"} },
"nested": {
"path": "users",
"query": {
"bool": {
"must": [ {"term": {"users.id": "user1"} }]
}
}
}
}
]
}
}}
我參考了以下鏈接來執行此操作: https://medium.com/@mena.meseha/briefly-describe-how-to-store-complex-relational-data-in-elasticsearch-f30277317b1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.