如何按列表中的现有状态排序



我正在使用ElasticSearch构建一个显示书籍列表的应用程序。每本书都可以标记为收藏夹。该页面将在当前用户的结果列表顶部显示收藏的书籍。

以下是一些对象

public class User {
  private String id;
  private String name;
  //getters/setters
}

公文

public class Book
{
   private String name;
   private List<User> favoriteOfUsers;
   //getters/setters
}

我想搜索列表并命令他们获取结果列表顶部当前用户的收藏夹书籍。请告诉我如何为此用例构建解决方案?

我想你正在寻找Elasticsearch的排序选项:https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-sort.html

假设收藏书籍的用户以嵌套列表的形式存储在书籍文档中,您可能希望在 Elasticsearch 的sort中使用 nested_filter 选项:

"sort" : [
   {
      "book" : {
         "mode" :  "avg",
         "order" : "asc",
         "nested_path" : "favouriteOfUsers",
         "nested_filter" : {
            "term" : { "favouriteOfUsers.id" : 1234 }
         }
      }
   }
]

希望这为您指明了正确的方向。

您可以使用函数评分。假设您的文档类型为:

  {
        "_index": "book",
        "_type": "book",
        "_id": "1",
        "_score": 1,
        "_source": {
           "name": "book1",
           "favoriteOfUsers": [
              {
                 "id": 1,
                // other properties of user
              },
              {
                 "id": 2,
               // other properties of user
              },
              {
                 "id": 3,
                 // other properties of user
              }
           ]
        }
     }

您可以使用以下查询

POST book/book/_search
{
"query": {
  "function_score": {
     "query": {
        "match_all": {}
     },
     "functions": [
        {
           "script_score": {
              "script": "if(_source.favoriteOfUsers*.id.contains(id)) {_score*10} else _score",
              "params": {
                 "id": 5
              }
           }
        }
     ]
     }
   } 
 }

如果您担心安全性,则可以使用此运行时髦脚本而无需动态脚本

最新更新