PageRenderTime 30ms CodeModel.GetById 13ms app.highlight 13ms RepoModel.GetById 0ms app.codeStats 1ms

/new_backend/abdelrahmanrustom-searchengine-ac46608ebeab/searches/commands/SearchCommand.java

https://bitbucket.org/abdelrahmanrustom/searchengine
Java | 175 lines | 127 code | 20 blank | 28 comment | 17 complexity | 1e3a9ca6ad78f932080ad4ce1c506cce MD5 | raw file
  1import com.google.gson.Gson;
  2import com.google.gson.JsonObject;
  3import com.mongodb.MongoClient;
  4import com.mongodb.MongoClientURI;
  5import com.mongodb.client.MongoCollection;
  6import com.mongodb.client.MongoDatabase;
  7import org.apache.http.HttpHost;
  8import org.bson.Document;
  9import org.elasticsearch.action.ActionListener;
 10import org.elasticsearch.action.search.SearchRequest;
 11import org.elasticsearch.action.search.SearchRequestBuilder;
 12import org.elasticsearch.action.search.SearchResponse;
 13import org.elasticsearch.client.RestClient;
 14import org.elasticsearch.client.RestHighLevelClient;
 15import org.elasticsearch.common.document.DocumentField;
 16import org.elasticsearch.index.query.BoolQueryBuilder;
 17import org.elasticsearch.index.query.QueryBuilder;
 18import org.elasticsearch.index.query.QueryBuilders;
 19import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
 20import org.elasticsearch.search.SearchHit;
 21import org.elasticsearch.search.SearchHits;
 22import org.elasticsearch.search.builder.SearchSourceBuilder;
 23import org.tartarus.snowball.ext.PorterStemmer;
 24
 25import java.io.IOException;
 26import java.io.StringReader;
 27import java.util.*;
 28import java.util.concurrent.Callable;
 29//https://github.com/harryaskham/Twitter-L-LDA/blob/master/util/Stopwords.java
 30import static org.elasticsearch.index.query.QueryBuilders.*;
 31
 32public class SearchCommand implements Callable<String> {
 33    String q;
 34    int resultType = 0, page_no = 1, category = -1, user_id = -1;
 35    boolean disableSpellingCorrection = false;
 36
 37    PorterStemmer porterStemmer = new PorterStemmer();
 38    final RestHighLevelClient client = new RestHighLevelClient(
 39            RestClient.builder(
 40                    new HttpHost("localhost", 9200, "http"),
 41                    new HttpHost("localhost", 9201, "http")));
 42
 43    private static final MongoClient mongoClient = new
 44            MongoClient(new MongoClientURI("mongodb://localhost:27017"));
 45    private  static  final MongoDatabase database = mongoClient.getDatabase("history");
 46    private static final MongoCollection<Document> collection = database.getCollection("user_history");
 47
 48    private static String[] stopwords = {"a", "as", "able", "about", "above", "according", "accordingly", "across", "actually", "after", "afterwards", "again", "against", "aint", "all", "allow", "allows", "almost", "alone", "along", "already", "also", "although", "always", "am", "among", "amongst", "an", "and", "another", "any", "anybody", "anyhow", "anyone", "anything", "anyway", "anyways", "anywhere", "apart", "appear", "appreciate", "appropriate", "are", "arent", "around", "as", "aside", "ask", "asking", "associated", "at", "available", "away", "awfully", "be", "became", "because", "become", "becomes", "becoming", "been", "before", "beforehand", "behind", "being", "believe", "below", "beside", "besides", "best", "better", "between", "beyond", "both", "brief", "but", "by", "cmon", "cs", "came", "can", "cant", "cannot", "cant", "cause", "causes", "certain", "certainly", "changes", "clearly", "co", "com", "come", "comes", "concerning", "consequently", "consider", "considering", "contain", "containing", "contains", "corresponding", "could", "couldnt", "course", "currently", "definitely", "described", "despite", "did", "didnt", "different", "do", "does", "doesnt", "doing", "dont", "done", "down", "downwards", "during", "each", "edu", "eg", "eight", "either", "else", "elsewhere", "enough", "entirely", "especially", "et", "etc", "even", "ever", "every", "everybody", "everyone", "everything", "everywhere", "ex", "exactly", "example", "except", "far", "few", "ff", "fifth", "first", "five", "followed", "following", "follows", "for", "former", "formerly", "forth", "four", "from", "further", "furthermore", "get", "gets", "getting", "given", "gives", "go", "goes", "going", "gone", "got", "gotten", "greetings", "had", "hadnt", "happens", "hardly", "has", "hasnt", "have", "havent", "having", "he", "hes", "hello", "help", "hence", "her", "here", "heres", "hereafter", "hereby", "herein", "hereupon", "hers", "herself", "hi", "him", "himself", "his", "hither", "hopefully", "how", "howbeit", "however", "i", "id", "ill", "im", "ive", "ie", "if", "ignored", "immediate", "in", "inasmuch", "inc", "indeed", "indicate", "indicated", "indicates", "inner", "insofar", "instead", "into", "inward", "is", "isnt", "it", "itd", "itll", "its", "its", "itself", "just", "keep", "keeps", "kept", "know", "knows", "known", "last", "lately", "later", "latter", "latterly", "least", "less", "lest", "let", "lets", "like", "liked", "likely", "little", "look", "looking", "looks", "ltd", "mainly", "many", "may", "maybe", "me", "mean", "meanwhile", "merely", "might", "more", "moreover", "most", "mostly", "much", "must", "my", "myself", "name", "namely", "nd", "near", "nearly", "necessary", "need", "needs", "neither", "never", "nevertheless", "new", "next", "nine", "no", "nobody", "non", "none", "noone", "nor", "normally", "not", "nothing", "novel", "now", "nowhere", "obviously", "of", "off", "often", "oh", "ok", "okay", "old", "on", "once", "one", "ones", "only", "onto", "or", "other", "others", "otherwise", "ought", "our", "ours", "ourselves", "out", "outside", "over", "overall", "own", "particular", "particularly", "per", "perhaps", "placed", "please", "plus", "possible", "presumably", "probably", "provides", "que", "quite", "qv", "rather", "rd", "re", "really", "reasonably", "regarding", "regardless", "regards", "relatively", "respectively", "right", "said", "same", "saw", "say", "saying", "says", "second", "secondly", "see", "seeing", "seem", "seemed", "seeming", "seems", "seen", "self", "selves", "sensible", "sent", "serious", "seriously", "seven", "several", "shall", "she", "should", "shouldnt", "since", "six", "so", "some", "somebody", "somehow", "someone", "something", "sometime", "sometimes", "somewhat", "somewhere", "soon", "sorry", "specified", "specify", "specifying", "still", "sub", "such", "sup", "sure", "ts", "take", "taken", "tell", "tends", "th", "than", "thank", "thanks", "thanx", "that", "thats", "thats", "the", "their", "theirs", "them", "themselves", "then", "thence", "there", "theres", "thereafter", "thereby", "therefore", "therein", "theres", "thereupon", "these", "they", "theyd", "theyll", "theyre", "theyve", "think", "third", "this", "thorough", "thoroughly", "those", "though", "three", "through", "throughout", "thru", "thus", "to", "together", "too", "took", "toward", "towards", "tried", "tries", "truly", "try", "trying", "twice", "two", "un", "under", "unfortunately", "unless", "unlikely", "until", "unto", "up", "upon", "us", "use", "used", "useful", "uses", "using", "usually", "value", "various", "very", "via", "viz", "vs", "want", "wants", "was", "wasnt", "way", "we", "wed", "well", "were", "weve", "welcome", "well", "went", "were", "werent", "what", "whats", "whatever", "when", "whence", "whenever", "where", "wheres", "whereafter", "whereas", "whereby", "wherein", "whereupon", "wherever", "whether", "which", "while", "whither", "who", "whos", "whoever", "whole", "whom", "whose", "why", "will", "willing", "wish", "with", "within", "without", "wont", "wonder", "would", "would", "wouldnt", "yes", "yet", "you", "youd", "youll", "youre", "youve", "your", "yours", "yourself", "yourselves", "zero"};
 49    private static Set<String> stopWordSet = new HashSet<String>(Arrays.asList(stopwords));
 50
 51    public SearchCommand(String q){
 52        this.q = q;
 53    }
 54
 55    public SearchCommand(String q, int resultType, int page_no, int category,
 56                         boolean disableSpellingCorrection, int user_id){
 57        this.q = q;
 58        this.resultType = resultType;
 59        this.page_no = page_no;
 60        this.category = category;
 61        this.disableSpellingCorrection = disableSpellingCorrection;
 62        this.user_id = user_id;
 63    }
 64
 65    private static boolean isStopword(String word) {
 66        if(word.length() < 2) return true;
 67        if(word.charAt(0) >= '0' && word.charAt(0) <= '9') return true; //remove numbers, "25th", etc
 68        if(stopWordSet.contains(word)) return true;
 69        else return false;
 70    }
 71
 72    private String removeStopWordsAndStem(String[] string) {
 73        String result = "";
 74        for(String word : string) {
 75            if(word.isEmpty()) continue;
 76            if(isStopword(word)) continue; //remove stopwords
 77            porterStemmer.setCurrent(word);
 78            porterStemmer.stem();
 79            result += (porterStemmer.getCurrent()+" ");
 80
 81        }
 82        return result;
 83    }
 84
 85    // TODO: max number of pages = 20
 86    public String call(){
 87        final String[] res = {null};
 88        String[] words = q.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+");;
 89        q = removeStopWordsAndStem(words);
 90
 91        SearchRequest searchRequest = new SearchRequest("webpages");
 92        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
 93        searchSourceBuilder.from(10*page_no);
 94        searchSourceBuilder.size(10*page_no - 1);
 95        BoolQueryBuilder tmp = QueryBuilders.boolQuery()
 96                .must(QueryBuilders.matchQuery("plain_text",
 97                        q))
 98                .should(QueryBuilders.matchQuery("keywords", q));
 99
100        if(category != -1)
101            tmp = tmp.must(QueryBuilders.termQuery("category", category));
102
103        if(resultType == 1)
104            tmp = tmp.filter(QueryBuilders.termQuery("has_imgs", true));
105        if(resultType == 1)
106            tmp = tmp.filter(QueryBuilders.termQuery("has_vids", true));
107
108
109        searchSourceBuilder.query(tmp);
110        searchRequest.source(searchSourceBuilder);
111        Map<String, Object> resJson = new HashMap<>();
112
113        if(page_no > 20){
114            return "{\"error\": \"Maximum number of pages exceeded\"}";
115        }
116
117        if(user_id > 0){
118            try {
119                Document d = new Document();
120                d.put("user_id", user_id);
121                d.put("query", q);
122                collection.insertOne(d);
123            }catch (Exception e){
124                resJson.put("error", e.toString());
125                Gson json = new Gson();
126                res[0] = json.toJson(resJson);
127                return res[0];
128            }
129        }
130
131        try {
132           SearchHits hits =  client.search(searchRequest).getHits();
133            ArrayList<String> json_search_responses = new ArrayList<>();
134            for(SearchHit hit: hits){
135                json_search_responses.add(hit.getSourceAsString());
136            }
137//                System.out.println(json_search_responses);
138            resJson.put("results", json_search_responses);
139            Gson json = new Gson();
140            res[0] = json.toJson(resJson);
141//            System.out.println(res[0]);
142            return res[0];
143        } catch (IOException e) {
144            resJson.put("error", e.toString());
145            Gson json = new Gson();
146            res[0] = json.toJson(resJson);
147            return res[0];
148        }
149//        client.searchAsync(searchRequest, new ActionListener<SearchResponse>() {
150//            @Override
151//            public void onResponse(SearchResponse searchResponse) {
152//                SearchHits hits = searchResponse.getHits();
153//                ArrayList<String> json_search_responses = new ArrayList<>();
154//                for(SearchHit hit: hits){
155//                   json_search_responses.add(hit.getSourceAsString());
156//                }
157////                System.out.println(json_search_responses);
158//                resJson.put("results", json_search_responses);
159//                Gson json = new Gson();
160//                res[0] = json.toJson(resJson);
161//                System.out.println(res[0]);
162//            }
163//
164//            @Override
165//            public void onFailure(Exception e) {
166//                resJson.put("error", e.toString());
167//                Gson json = new Gson();
168//                res[0] = json.toJson(resJson);
169//            }
170//        });
171
172//        while (!(res[0] == null));
173//        return res[0];
174    }
175}