javaopenldapapache-directory

How to do a sorted search using Apache Directory API


I am using the Apache Directory API to query an OpenLDAP server. I think this code should return the results sorted by sn but they are returned in random order.

    SearchRequest req = new SearchRequestImpl();
    req.setScope(SearchScope.ONELEVEL);
    req.addAttributes("*");
    req.setTimeLimit(0);
    req.setBase(searchDn);
    req.setFilter("(objectclass=posixAccount)");

    SortRequest sortRequest = new SortRequestControlImpl();
    sortRequest.addSortKey(new SortKey("sn"));
    req.addControl(sortRequest);

    try (EntryCursor cursor = new EntryCursorImpl(connection.search(req))) {        
        for (Entry entry : cursor) {
            System.out.println("sn: " + entry.get("sn").getString());                
        }
    }

The output of this code from the data in my test LDAP Server is:

sn: Trainee 
sn: Admin 
sn: User 
sn: Supervisor 
sn: Supervisor

I based the code on this Integration test https://github.com/apache/directory-server/blob/master/server-integ/src/test/java/org/apache/directory/server/operations/search/SortedSearchIT.java and I can't see what I have done wrong.

Can anyone offer any advice? Thanks.


Solution

  • After much digging, I had to do two things to get this to work.

    First add sssvlv support to my OpenLDAP server

    This is the ldif

    dn: cn=module{0}, cn=config
    changetype: modify
    add: olcModuleLoad
    olcModuleLoad: sssvlv.la
    
    dn: olcOverlay=sssvlv,olcDatabase={1}hdb,cn=config
    changetype: add
    objectClass: olcSssVlvConfig
    olcSssVlvMax: 10
    olcSssVlvMaxKeys: 5
    

    Then I had to specify the Matching Rule ID for the sort key

    SortKey sk = new SortKey( "sn", SchemaConstants.NUMERIC_STRING_ORDERING_MATCH_MR_OID);
    

    Hopefully this will help someone!