Subversion Repositories SmartDukaan

Rev

Rev 34187 | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.common.solr;

import com.spice.profitmandi.common.enumuration.SchemeType;
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.web.client.RestClient;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service("solrServiceCommon")
public class SolrService {

        private static final Logger logger = LogManager.getLogger(SolrService.class);

        @Value("${new.solr.url}")
        private String solrUrl;

        @Autowired
        private RestClient restClient;

        public String getContent(String queryTerm, List<Integer> categoryIds, List<String> brands, int limit,
                        boolean activeOnly) throws Exception {

                JSONArray docs = this.getContentDocs(queryTerm, categoryIds, brands, limit, activeOnly);
                return docs.toString();
        }

        public JSONArray getContentDocs(String queryTerm, List<Integer> categoryIds, List<String> brands, int limit,
                        boolean activeOnly) throws Exception {
                Map<String, String> params = new HashMap<>();
                List<String> mandatoryQ = new ArrayList<>();
                if (queryTerm != null && !queryTerm.equals("null")) {
                        mandatoryQ.add(String.format("+(%s)", "*" + queryTerm + "*"));
                } else {
                        queryTerm = null;
                }
                params.put("q", StringUtils.join(mandatoryQ, " "));
                if (categoryIds != null && categoryIds.size() > 0) {
                        params.put("q", params.get("q") + " +filter(categoryId_i:(" + StringUtils.join(categoryIds, " ") + "))");
                }
                if (brands.size() > 0) {
                        brands = brands.stream().map(x -> x.replaceAll(" ", "\\\\ ")).collect(Collectors.toList());
                        params.put("q", params.get("q") + " AND brand_ss:(" + StringUtils.join(brands, " ") + ")");
                }
                if (activeOnly) {
                        params.put("q", params.get("q") + " AND active_b:true");
                }
                params.put("fl", "*");
                if (queryTerm == null) {
                        params.put("sort", "create_s desc");
                }
                params.put("start", String.valueOf(0));
                if (limit == 0) {
                        params.put("fl", "catalogId_i, title_s");
                        params.put("rows", String.valueOf(5000));
                } else {
                        params.put("rows", String.valueOf(limit));
                }
                params.put("wt", "json");
                String response = null;
                try {
                        response = restClient.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
                } catch (HttpHostConnectException e) {
                        throw new ProfitMandiBusinessException("", "", "Could not connect to host");
                }
                JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
                JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
                return docs;
        }

        public Map<Integer, JSONObject> getContentByCatalogIds(List<Integer> catalogIds) throws Exception {
                Map<Integer, JSONObject> documentMap = new HashMap<>();
                Map<String, String> params = new HashMap<>();
                params.put("q", "catalogId_i:" + StringUtils.join(catalogIds, " "));
                params.put("fl", "*");
                params.put("start", String.valueOf(0));
                params.put("rows", String.valueOf(100));
                params.put("wt", "json");
                String response = null;
                try {
                        response = restClient.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
                } catch (HttpHostConnectException e) {
                        throw new ProfitMandiBusinessException("", "", "Could not connect to host");
                }
                JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
                JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
                for (int i = 0; i < docs.length(); i++) {
                        JSONObject doc = docs.getJSONObject(i);
                        documentMap.put(doc.getInt("catalogId_i"), doc);
                }
                return documentMap;
        }

        // This method is the used to pull docs based on search and shall be used
        // interchangably for both the things
        public JSONArray getSolrDocs(String queryTerm, String categoryId, int offset, int limit, String sort,
                        String brand, int subCategoryId, boolean hotDeal, boolean group, boolean eol_filter) throws Throwable {
                List<String> parentFilter = new ArrayList<>();
                parentFilter.add("categoryId_i:" + categoryId);
                parentFilter.add("show_default_b:true");
                List<String> childFilter = new ArrayList<>();
                childFilter.add("itemId_i:*");

                Map<String, String> params = new HashMap<>();
                if (queryTerm == null || queryTerm.equals("null")) {
                        queryTerm = "";
                } else {
                        queryTerm = "(" + queryTerm + ")";
                }
                if (hotDeal) {
                        childFilter.add("hot_deal_b:true");
                } else {
                        childFilter.add("active_b:true");
                }
                if (subCategoryId != 0) {
                        parentFilter.add("subCategoryId_i:" + subCategoryId);
                }

                if(eol_filter){
                        parentFilter.add("eol_no_stock_b:false");
                }
                if (StringUtils.isNotBlank(brand)) {
                        parentFilter.add("brand_ss:" + "\\\"" + brand + "\\\"");
                }
                if (queryTerm == "") {
                        params.put("sort", (sort == "" ? "" : sort + ", ") + "create_s desc");
                } else {
                        parentFilter.addAll(Arrays.asList(queryTerm.split(" ")));
                }
                String parentFilterString = "\"" + String.join(" AND ", parentFilter) + "\"";
                String childFilterString = String.join(" AND ", childFilter);
                params.put("q", String.format("{!parent which=%s}%s", parentFilterString, childFilterString));
                params.put("fl",
                                String.format("*, [child parentFilter=id:catalog* childFilter=%s]", "\"" + childFilterString + "\""));
                params.put("start", String.valueOf(offset));
                params.put("rows", String.valueOf(limit));
                params.put("wt", "json");

                String groupByField = null;

                if (group) {
                        groupByField = "superCatalog_s";
                        params.put("group", String.valueOf(group));
                        params.put("group.field", groupByField);
                        params.put("group.limit", "1");
                        if (!sort.isEmpty()) {
                                params.put("group.sort", sort);
                        }
                }
logger.info("groupByField {}", groupByField);
                String response = null;

                try {
                        response = restClient.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
                } catch (HttpHostConnectException e) {
                        throw new ProfitMandiBusinessException("", "", "Could not connect to host");
                }

                /*JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
                JSONArray docs = solrResponseJSONObj.getJSONArray("docs");*/

                JSONObject solrResponseJSONObj = new JSONObject(response);
                JSONArray docs;

                if (group) {
                        logger.info("Reached in if condition {}",groupByField);
                        JSONObject grouped = solrResponseJSONObj.getJSONObject("grouped");
                        JSONArray groups = grouped.getJSONObject(groupByField).getJSONArray("groups");

                        docs = new JSONArray();
                        for (int i = 0; i < groups.length(); i++) {
                                JSONObject groupObj = groups.getJSONObject(i);
                                JSONArray groupDocs = groupObj.getJSONObject("doclist").getJSONArray("docs");
                                for (int j = 0; j < groupDocs.length(); j++) {
                                        docs.put(groupDocs.getJSONObject(j));
                                }
                        }
                } else {
                        logger.info("Reached in else condition {}",groupByField);
                        docs = solrResponseJSONObj.getJSONObject("response").getJSONArray("docs");
                }

                logger.info("Reached at end {}",docs);

                return docs;
        }

}