天天看點

8.7 SpringBoot內建ElasticSearch之排序

1.condition開發

在項目目錄“/src/main/java/com/example/es/condition”的EmployeeCondition類中實作SortProvider接口,具體代碼如下。

@Data
public class EmployeeCondition extends SampleEmployeeCondition implements RoutingProvider, ScoreFunctionProvider, SortProvider {
    private static final Sort[] SORTS = {
            //年齡升序
            Sort.fieldAsc("age"),
            //薪水降序
            Sort.fieldDesc("salary"),
    };

    @Override
    public Sort[] getSorts() {
        return SORTS;
    }
}      
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Resource
    private EmployeeMapper employeeMapper;

    @ResponseBody
    @RequestMapping(value = "/queryEmployeePage", method = RequestMethod.GET)
    public Page<EmployeeEntity> queryEmployeePage() {
        EmployeeCondition employeeCondition = new EmployeeCondition();
        employeeCondition.setJob("Java engineer");
        return employeeMapper.queryEmployeeList(employeeCondition);
    }
}      
[
    {
        "id": "10000002",
        "employeeId": "10000002",
        "name": "Stephen Curry",
        "age": 27,
        "birthday": "1995-08-06",
        "job": "Java engineer",
        "salary": 20000.0,
        "hobby": [
            "tennis",
            "football"
        ],
        "profile": {
            "nickName": "cupid",
            "avatar": "https://www.avatar.com/10000002.png",
            "grade": "golden"
        },
        "relative": [
            {
                "employeeId": "10000001"
            },
            {
                "employeeId": "10000003"
            }
        ]
    },
    {
        "id": "10000001",
        "employeeId": "10000001",
        "name": "James Harden",
        "age": 31,
        "birthday": "1991-01-01",
        "job": "Java engineer",
        "salary": 30000.0,
        "hobby": [
            "swimming",
            "running",
            "basketball",
            "football"
        ],
        "profile": {
            "nickName": "squirrel",
            "avatar": "https://www.avatar.com/10000001.png",
            "grade": "diamonds"
        },
        "relative": [
            {
                "employeeId": "10000002"
            },
            {
                "employeeId": "10000004"
            }
        ]
    }
]