]> git.somenet.org - pub/jan/dst18.git/blob - ass1-doc/src/main/java/dst/ass1/doc/impl/DocumentQuery.java
Fix all profile and add module to ass3-elastic profile
[pub/jan/dst18.git] / ass1-doc / src / main / java / dst / ass1 / doc / impl / DocumentQuery.java
1 package dst.ass1.doc.impl;
2
3 import com.mongodb.client.MapReduceIterable;
4 import com.mongodb.client.MongoCollection;
5 import com.mongodb.client.MongoDatabase;
6 import dst.ass1.doc.IDocumentQuery;
7 import dst.ass1.jpa.util.Constants;
8 import org.bson.Document;
9
10 import java.util.ArrayList;
11 import java.util.List;
12 import java.util.regex.Pattern;
13
14 import static com.mongodb.client.model.Filters.eq;
15 import static com.mongodb.client.model.Filters.regex;
16
17 public class DocumentQuery implements IDocumentQuery {
18     private MongoDatabase db;
19
20     public DocumentQuery(MongoDatabase db) {
21         this.db = db;
22     }
23
24     @Override
25     public Document findByMaterialId(Long materialId) {
26         MongoCollection<Document> coll = db.getCollection(Constants.COLL_MATERIAL_DATA);
27         return coll.find(eq(Constants.I_MATERIAL, materialId)).first();
28     }
29
30     @Override
31     public List<Long> findIdsByType(String typeSubstring) {
32         MongoCollection<Document> coll = db.getCollection(Constants.COLL_MATERIAL_DATA);
33         List<Long> ret = new ArrayList<>();
34         for (Document doc : coll.find(regex(Constants.M_MATERIAL_TYPE, ".*" + Pattern.quote(typeSubstring) + ".*"))) {
35             ret.add(Long.valueOf("" + doc.get(Constants.I_MATERIAL)));
36         }
37
38         return ret;
39     }
40
41     @Override
42     public List<Document> getDocumentStatistics() {
43         MongoCollection coll = db.getCollection(Constants.COLL_MATERIAL_DATA);
44
45         String map = "function(){if(this.type=='quiz')emit(this.quiz_type,this.questions.length);}";
46         String reduce = "function(key, values) { " +
47                 "var result = 0;" +
48                 "values.forEach(function(value){result += value;});" +
49                 "return result;}";
50
51         MapReduceIterable<Document> iter = coll.mapReduce(map, reduce);
52         ArrayList<Document> a = iter.into(new ArrayList<Document>());
53         return a;
54     }
55
56 }