1 package search.db;
2 
3 import util.ConnectionUtil;
4 import util.SearchUtil;
5 import util.TableOperations;
6 import chemaxon.jchem.db.JChemSearch;
7 import chemaxon.sss.SearchConstants;
8 import chemaxon.sss.search.JChemSearchOptions;
9 import chemaxon.util.ConnectionHandler;
10
11/**
12 * Example codes for ordering hits of database search.
13 * 
14 * @author JChem Base team, ChemAxon Ltd.
15 */
16public final class SortedSearchExample {
17
18    private static final String TABLE_NAME = "demo";
19
20    private ConnectionHandler connHandler;
21
22    public static void main(String[] args) {
23        try {
24            new SortedSearchExample().run();
25        } catch (Exception e) {
26            e.printStackTrace();
27        }
28    }
29
30    private void run() throws Exception {
31        connHandler = ConnectionUtil.connectToDB();
32        try {
33            TableOperations.setupMoleculeTable(connHandler, TABLE_NAME);
34            runSearches();
35        } finally {
36            ConnectionUtil.closeConnection(connHandler);
37        }
38    }
39
40    private void runSearches() throws Exception {
41
42        JChemSearchOptions searchOpts = new JChemSearchOptions(SearchConstants.SIMILARITY);
43
44        searchOpts.setDissimilarityThreshold(0.6f);
45
46        JChemSearch jcs =
47                SearchUtil.createJChemSearch(connHandler, "c1ccccc1N", TABLE_NAME, searchOpts);
48
49        // Change the default which is by similarity and id:
50        jcs.setOrder(JChemSearch.ORDERING_BY_ID);
51        jcs.run();
52
53        System.out.printf("%d hit(s) found (in ID order)\n", jcs.getResultCount());
54        printResult(jcs);
55
56        jcs.getSearchOptions().setFilterQuery("SELECT cd_id FROM " + TABLE_NAME
57                + " ORDER BY cd_molweight");
58        jcs.run();
59        System.out.println();
60        System.out.printf("%d hit(s) found (in molweight order)\n", jcs.getResultCount());
61        printResult(jcs);
62    }
63
64    private void printResult(JChemSearch jcs) {
65        int[] cdIds = jcs.getResults();
66        for (int i = 0; i < cdIds.length; i++) {
67            int cdId = cdIds[i];
68            float dissim = jcs.getDissimilarity(i);
69            System.out.printf("cd_id: %d dissimilarity: %.3f\n", cdId, dissim);
70        }
71    }
72
73}
74