Skip to content

Metadata Search Example

Stu Arnett edited this page Aug 11, 2016 · 1 revision

Here is a simple example of using metadata search with S3Client. Suppose that you created a bucket to hold images, and that (during creation) you added a search key for the view-count user metadata key (x-amz-meta-view-count). Let's also suppose that there are 1000 images in the bucket and 3 of them have a view-count greater than 10,000. Here is the code that would find those images and also provide the size and mtime for each:

        QueryObjectsRequest request = new QueryObjectsRequest("image-bucket")
                .withAttribute("LastModified") // adds mtime to the results
                .withAttribute("Size") // adds size to the results
                .withQuery("x-amz-meta-view-count>10000");
        QueryObjectsResult result = client.queryObjects(request);

        // these are all of the matches
        for (QueryObject queryObject : result.getObjects()) {
            System.out.println(queryObject.getObjectName());
            String viewCount = null;
            // attributes you requested plus any indexed keys are available as query metadata
            for (QueryMetadata queryMetadata : queryObject.getQueryMds()) {
                System.out.println(" - " + queryMetadata.getType()); // SYSMD or USERMD
                for (Map.Entry<String, String> entry : queryMetadata.getMdMap().entrySet()) {
                    System.out.println(" - - " + entry.getKey() + ": " + entry.getValue());
                }
                // you can also pull a specific indexed key from the map
                if (queryMetadata.getType() == QueryMetadataType.USERMD)
                    viewCount = queryMetadata.getMdMap().get("x-amz-meta-view-count");
            }
            System.out.println("View Count: " + viewCount);
        }

This code will output the following, given the assumptions above:

bigfoot.jpg
 - SYSMD
 - - mtime: 1470947981862
 - - size: 435672
 - USERMD
 - - x-amz-meta-view-count: 60812
View Count: 60812
crazy-kitten.jpg
 - SYSMD
 - - mtime: 1470947519845
 - - size: 1954876
 - USERMD
 - - x-amz-meta-view-count: 11284
View Count: 11284
plane-crash.jpg
 - SYSMD
 - - mtime: 1470942845794
 - - size: 2491584
 - USERMD
 - - x-amz-meta-view-count: 24819
View Count: 24819
Clone this wiki locally