PageRenderTime 45ms CodeModel.GetById 29ms app.highlight 14ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/abdelrahmanrustom/searchengine
Java | 137 lines | 99 code | 12 blank | 26 comment | 5 complexity | 62b0d9de6e7c2adbe0151f40400b8eb8 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.FindIterable;
  6import com.mongodb.client.MongoCollection;
  7import com.mongodb.client.MongoDatabase;
  8import org.apache.http.HttpHost;
  9import org.bson.Document;
 10import org.elasticsearch.action.ActionListener;
 11import org.elasticsearch.action.search.SearchRequest;
 12import org.elasticsearch.action.search.SearchRequestBuilder;
 13import org.elasticsearch.action.search.SearchResponse;
 14import org.elasticsearch.client.RestClient;
 15import org.elasticsearch.client.RestHighLevelClient;
 16import org.elasticsearch.common.document.DocumentField;
 17import org.elasticsearch.index.query.BoolQueryBuilder;
 18import org.elasticsearch.index.query.QueryBuilder;
 19import org.elasticsearch.index.query.QueryBuilders;
 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 com.mongodb.client.model.Filters.eq;
 31import java.util.Random;
 32import static org.elasticsearch.index.query.QueryBuilders.*;
 33
 34public class RecommendNewMaterialCommand implements Callable<String> {
 35    int user_id = -1;
 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("interests");
 47    private static final MongoCollection<Document> collection1 = database.getCollection("history");
 48    Random random = new Random();
 49
 50    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"};
 51    private static Set<String> stopWordSet = new HashSet<String>(Arrays.asList(stopwords));
 52
 53    public RecommendNewMaterialCommand(int user_id){
 54        this.user_id = user_id;
 55    }
 56
 57    public String call(){
 58        final String[] res = {null};
 59        String keywords = "";
 60        String error = null;
 61        int interest = 1;
 62
 63        Document d1 =null;
 64        FindIterable<Document> d2 =null;
 65        try {
 66            d1 = collection.find(eq("user_id", user_id)).first();
 67            int[] _interests = (int[]) d1.get("interests");
 68            interest = _interests[random.nextInt(4)];
 69            d2 = collection1.find(eq("user_id", user_id));
 70            int i = 0;
 71            for(Document d: d2){
 72                keywords += d.getString("query") + " ";
 73                if(++i > 5)
 74                    break;
 75            }
 76
 77        }catch (Exception e){
 78            error = e.toString();
 79        }
 80
 81        if(error != null){
 82            return "{\"error\":" + error + " }";
 83        }
 84
 85        SearchRequest searchRequest = new SearchRequest("webpages");
 86        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
 87        BoolQueryBuilder tmp = QueryBuilders.boolQuery()
 88                .must(QueryBuilders.matchQuery("category",
 89                        interest))
 90                .should(QueryBuilders.matchQuery("keywords", keywords));
 91
 92        searchSourceBuilder.query(tmp);
 93        searchRequest.source(searchSourceBuilder);
 94        Map<String, Object> resJson = new HashMap<>();
 95        try {
 96            SearchHits hits =  client.search(searchRequest).getHits();
 97            ArrayList<String> json_search_responses = new ArrayList<>();
 98            for(SearchHit hit: hits){
 99                json_search_responses.add(hit.getSourceAsString());
100            }
101//                System.out.println(json_search_responses);
102            resJson.put("results", json_search_responses);
103            Gson json = new Gson();
104            res[0] = json.toJson(resJson);
105//            System.out.println(res[0]);
106            return res[0];
107        } catch (IOException e) {
108            resJson.put("error", e.toString());
109            Gson json = new Gson();
110            res[0] = json.toJson(resJson);
111            return res[0];
112        }
113//        client.searchAsync(searchRequest, new ActionListener<SearchResponse>() {
114//            @Override
115//            public void onResponse(SearchResponse searchResponse) {
116//                SearchHits hits = searchResponse.getHits();
117//                ArrayList<String> json_search_responses = new ArrayList<>();
118//                for(SearchHit hit: hits){
119//                    json_search_responses.add(hit.getSourceAsString());
120//                }
121////                System.out.println(json_search_responses);
122//                resJson.put("results", json_search_responses);
123//                Gson json = new Gson();
124//                res[0] = json.toJson(resJson);
125//            }
126//
127//            @Override
128//            public void onFailure(Exception e) {
129//                resJson.put("error", e.toString());
130//                Gson json = new Gson();
131//                res[0] = json.toJson(resJson);
132//            }
133//        });
134//        while (!(res[0] == null));
135//        return res[0];
136    }
137}