changed search behaviour

This commit is contained in:
Timo Volkmann 2020-06-23 00:14:49 +02:00
parent cdda87f3c6
commit c347b79f02
3 changed files with 291 additions and 258 deletions

View File

@ -57,25 +57,41 @@ function searchHandler(dbConn) {
//response.data = searchResults //response.data = searchResults
const cutScores = !(_.isEmpty(scoreQueryObj.climate) && _.isEmpty(scoreQueryObj.costs) && _.isEmpty(scoreQueryObj.others)) const cutScores = !(_.isEmpty(scoreQueryObj.climate) && _.isEmpty(scoreQueryObj.costs) && _.isEmpty(scoreQueryObj.others))
//console.log(cutScores);
const queryCounter = _.keys(q).length - 2
// TODO only dev:
searchResults.forEach(reg => reg.name = `${reg.name} (${_.round(reg.score * 10, 1)}% match)`)
// FILTER NULLSCORES // FILTER NULLSCORES
if (!_.get(q, 'showRegionsWithNullScore', false)) { if (!_.get(q, 'showRegionsWithNullScore', false)) {
console.log('without null scores'); console.log('without null scores');
searchResults = searchResults.filter(el => !_.some(el.scores, score => _.isNaN(score.score) || _.isNil(score.score)/* || score.score <= 0*/)).filter(el => { searchResults.forEach(el => console.log('region:', el.name, 'score:', el.score))
//searchResults = searchResults.filter(el => !_.some(el.scores, score => _.isNaN(score.score) || _.isNil(score.score)/* || score.score <= 0*/))
searchResults = searchResults.filter(el => !(_.isNil(el.score) || _.isNaN(el.score)) )
// searchResults = searchResults.filter(el => {
// let nullcnt = 0
// el.scores.forEach(sc => {
// if (_.isNaN(sc.score) || sc.score <= 0 || _.isNil(el.score)) {
// nullcnt++
// }
// })
// console.log(el.name, nullcnt)
// return nullcnt >= 2 ? false : true
// })
/*searchResults = searchResults.filter(el => {
console.log('scorrrrrr', el.score); console.log('scorrrrrr', el.score);
let keepIt = true let keepIt = true
if (_.some(el.scores, score => score.score <= 0) && el.score < 1) keepIt = false //if (_.some(el.scores, score => score.score <= 0) && el.score < 1) keepIt = false
return cutScores ? keepIt : true return cutScores ? keepIt : true
})//.filter(el => !_.isNaN(el.score)) })//.filter(el => !_.isNaN(el.score))*/
} }
// SEND RESPONSE // SEND RESPONSE
if (_.isEmpty(searchResults)) { if (_.isEmpty(searchResults)) {
res.status(404).send('No regions found with your parameters') res.status(204).json(searchResults)
return return
} }
// response.data = searchResults
// res.json(response)
res.json(searchResults) res.json(searchResults)
}).catch(e => { }).catch(e => {

View File

@ -5,10 +5,8 @@ exports.calculateAvgScore = (...scores) => {
} }
exports.calculateScoreRange = (min, max, multiplier, regionVal, sLowVal, sHighVal) => { exports.calculateScoreRange = (min, max, multiplier, regionVal, sLowVal, sHighVal) => {
console.log('scores.calculateScoreRange:', min, max, multiplier, regionVal, sLowVal, sHighVal) //console.log('scores.calculateScoreRange:', min, max, multiplier, regionVal, sLowVal, sHighVal)
// return full score when in range // return full score when in range
console.log(regionVal >= sLowVal && regionVal <= sHighVal);
if (regionVal >= sLowVal && regionVal <= sHighVal) return 10; if (regionVal >= sLowVal && regionVal <= sHighVal) return 10;
// choose value with smallest distance // choose value with smallest distance
let sVal = Math.abs(regionVal - sLowVal) < Math.abs(regionVal - sHighVal) ? sLowVal : sHighVal; let sVal = Math.abs(regionVal - sLowVal) < Math.abs(regionVal - sHighVal) ? sLowVal : sHighVal;
@ -21,6 +19,12 @@ exports.calculateScore = (min, max, multiplier, regionVal, searchVal) => {
//return score <= 0 ? 0 : score * 10; //return score <= 0 ? 0 : score * 10;
} }
exports.linear = function (x, exponent) {
if (x < 0) return 0
if (x > 10) return 10
return x
}
exports.easeOut = function (x, exponent) { exports.easeOut = function (x, exponent) {
if (x < 0) return 0 if (x < 0) return 0
if (x > 10) return 10 if (x > 10) return 10

View File

@ -1,31 +1,31 @@
const _ = require('lodash') const _ = require('lodash')
const moment = require("moment") const moment = require("moment")
const getClimateMinMax = require("./getClimateMinMax.js") const getClimateMinMax = require("./getClimateMinMax.js")
const score = require('./score') const scorer = require('./score')
const getRegions = require('../models/getRegions.js') const getRegions = require('../models/getRegions.js')
const SHOW_ALL_SCOREOBJECTS = false const SHOW_ALL_SCOREOBJECTS = false
const MULTIPLIER = { const SETTINGS = {
temperature_mean_max: 5, temperature_mean_max: [4.5, 'easeOut', 2],
precipitation: 5, precipitation: [4, 'easeInOut', 2],
rain_days: 2, rain_days: [2, 'easeInOut', 2],
sun_hours: 1.8, sun_hours: [3.6, 'easeInOut', 2],
accommodation_costs: 17, accommodation_costs: [17, 'linear', null],
food_costs: 4, food_costs: [4, 'linear', null],
alcohol_costs: 4, alcohol_costs: [4, 'linear', null],
water_costs: 4, water_costs: [10, 'linear', null],
local_transportation_costs: 3, local_transportation_costs: [5, 'linear', null],
entertainment_costs: 3, entertainment_costs: [5, 'easeInOut', 0.6],
average_per_day_costs: 40, average_per_day_costs: [5, 'linear', null],
avg_price_relative: 3 avg_price_relative: [3, 'easeOut', 2],
} }
module.exports = function (dbConn) { module.exports = function (dbConn) {
return async function (regions, from, to, q) { return async function (regions, from, to, q) {
console.log('search') console.log('search')
if ((_.isNil(to) || _.isNil(from)) && !(_.isEmpty(q.climate) || _.isEmpty(q.costs))) { if ((_.isNil(to) || _.isNil(from)) && !(_.isEmpty(q.climate) || _.isEmpty(q.costs) || _.isEmpty(q.others))) {
throw new Error('invalid query') throw new Error('invalid query')
} }
// PREPARE SEARCH // PREPARE SEARCH
@ -74,13 +74,13 @@ module.exports = function (dbConn) {
// CALCULATE SCORES FOR CLIMATE PROPS // CALCULATE SCORES FOR CLIMATE PROPS
regions.forEach(reg => { regions.forEach(reg => {
Object.entries(q.climate).forEach(([key, value]) => { Object.entries(q.climate).forEach(([key, value]) => {
let finalScoreObj = calculateScoreForPeriod(key, travelPeriods, reg, value[0], value[1], boundaryClimate, 'easeInOut', 2) let finalScoreObj = calculateScoreForPeriod(key, travelPeriods, reg, value[0], value[1], boundaryClimate)
reg.scores.push(finalScoreObj) reg.scores.push(finalScoreObj)
}); });
// CALCULATE SCORES FOR PRICE PROPS // CALCULATE SCORES FOR PRICE PROPS
Object.entries(q.costs).forEach(([key, value]) => { Object.entries(q.costs).forEach(([key, value]) => {
let finalScoreObj = calculateSimpleScore(key, reg, value[0], value[1], boundaryStatic, 'easeInOut', 2) let finalScoreObj = calculateSimpleScore(key, reg, value[0], value[1], boundaryStatic)
reg.scores.push(finalScoreObj) reg.scores.push(finalScoreObj)
}); });
@ -93,8 +93,15 @@ module.exports = function (dbConn) {
reg.price_tendency_relative = getAverageFromTrivago(travelPeriods, reg) reg.price_tendency_relative = getAverageFromTrivago(travelPeriods, reg)
// CALCULATE AVERAGE SCORE // CALCULATE AVERAGE SCORE Stage 1
let scoreSubGroups = []
if (!_.isEmpty(q.climate)) scoreSubGroups.push(calculateAverage(reg.scores.filter(el => _.some(Object.keys(q.climate), entry => entry === el.type ) )) )
if (!_.isEmpty(q.costs)) scoreSubGroups.push(calculateAverage(reg.scores.filter(el => _.some(Object.keys(q.costs), entry => entry === el.type ))) )
if (!_.isEmpty(q.others)) scoreSubGroups.push(calculateAverage(reg.scores.filter(el => _.some(Object.keys(q.others), entry => entry === el.type ) )) )
// CALCULATE AVERAGE SCORE Stage 2
reg.score = calculateAverage(reg.scores) reg.score = calculateAverage(reg.scores)
// reg.score = _.sum(scoreSubGroups) / scoreSubGroups.length
}) })
return _.orderBy(regions, ({ score }) => score || 0, 'desc') //.filter(el => !_.isNaN(el.score)) return _.orderBy(regions, ({ score }) => score || 0, 'desc') //.filter(el => !_.isNaN(el.score))
} }
@ -107,7 +114,12 @@ module.exports = function (dbConn) {
cnt++ cnt++
sum += el.score sum += el.score
} }
if (el.score === null || el.score === undefined || _.isNaN(el.score)) {
cnt++
sum += -1
}
}) })
//if (sum === 0 && cnt === 0) return 0
return _.round(sum / cnt, 3) return _.round(sum / cnt, 3)
} }
@ -129,27 +141,6 @@ module.exports = function (dbConn) {
return travelPeriods return travelPeriods
} }
function createPeriod(from, to, currentMonth, currentYear) {
let period = {}
if (currentMonth === from.month && currentYear === from.year) {
period = {
month: currentMonth,
days: 32 - from.day
}
} else if (currentMonth === to.month) {
period = {
month: currentMonth,
days: to.day
}
} else {
period = {
month: currentMonth,
days: 30
}
}
return period
}
function validateDates(from, to) { function validateDates(from, to) {
let fromAndTo = { let fromAndTo = {
from: {}, from: {},
@ -181,8 +172,30 @@ module.exports = function (dbConn) {
return fromAndTo return fromAndTo
} }
function calculateScoreForPeriod(type, travelPeriods, region, searchLowParam, searchMaxParam, minMax, funcType, funcSlope) { function createPeriod(from, to, currentMonth, currentYear) {
console.log('getScoreAndAverageFromClimate for', region.name, type) let period = {}
if (currentMonth === from.month && currentYear === from.year) {
period = {
month: currentMonth,
days: 32 - from.day
}
} else if (currentMonth === to.month) {
period = {
month: currentMonth,
days: to.day
}
} else {
period = {
month: currentMonth,
days: 30
}
}
return period
}
function calculateScoreForPeriod(type, travelPeriods, region, searchLowParam, searchMaxParam, minMax) {
// console.log('getScoreAndAverageFromClimate for', region.name, type)
const singleScores = travelPeriods.map(period => { const singleScores = travelPeriods.map(period => {
let res = { let res = {
@ -204,30 +217,30 @@ module.exports = function (dbConn) {
averagedScore.value += (el.value * el.days) averagedScore.value += (el.value * el.days)
averagedScore.days += (el.days) averagedScore.days += (el.days)
} else { } else {
console.log('skip averaging') // console.log('skip averaging')
console.log(el) // console.log(el)
} }
}) })
averagedScore.value = _.round(averagedScore.value / averagedScore.days, 3) averagedScore.value = _.round(averagedScore.value / averagedScore.days, 3)
delete averagedScore.days delete averagedScore.days
let sc = score.calculateScoreRange(minMax.min[type], minMax.max[type], MULTIPLIER[type], averagedScore.value, searchLowParam, searchMaxParam) let sc = scorer.calculateScoreRange(minMax.min[type], minMax.max[type], SETTINGS[type][0], averagedScore.value, searchLowParam, searchMaxParam)
averagedScore.score = _.round(score[funcType](sc, funcSlope), 3) averagedScore.score = _.round(scorer[SETTINGS[type][1]](sc, SETTINGS[type][2]), 3)
console.log('score', averagedScore.score) // console.log('score', averagedScore.score)
if (searchLowParam === null) averagedScore.score = null if (searchLowParam === null) averagedScore.score = null
return averagedScore return averagedScore
} }
function calculateSimpleScore(type, region, searchLowParam, searchMaxParam, minMax, funcType, funcSlope) { function calculateSimpleScore(type, region, searchLowParam, searchMaxParam, minMax) {
console.log('getScoreFromCosts for', region.name, type) // console.log('getScoreFromCosts for', region.name, type)
const sc = _.round(score.calculateScoreRange(minMax.min[type], minMax.max[type], MULTIPLIER[type], region[type], searchLowParam, searchMaxParam), 3) const sc = _.round(scorer.calculateScoreRange(minMax.min[type], minMax.max[type], SETTINGS[type][0], region[type], searchLowParam, searchMaxParam), 3)
let finScore = { let finScore = {
type: type, type: type,
value: region[type], value: region[type],
score: score[funcType](sc, funcSlope), score: scorer[SETTINGS[type][1]](sc, SETTINGS[type][2]),
} }
finScore.value = _.round(finScore.value, 1) finScore.value = _.round(finScore.value, 1)
finScore.score = _.round(finScore.score, 3) finScore.score = _.round(finScore.score, 3)
@ -237,7 +250,7 @@ module.exports = function (dbConn) {
} }
function getAverageFromTrivago(travelPeriods, region) { function getAverageFromTrivago(travelPeriods, region) {
console.log('getAverageFromTrivago for', region.name) // console.log('getAverageFromTrivago for', region.name)
const singleScores = travelPeriods.map(period => { const singleScores = travelPeriods.map(period => {
let res = { let res = {
@ -253,12 +266,12 @@ module.exports = function (dbConn) {
days: 0 days: 0
} }
singleScores.forEach(el => { singleScores.forEach(el => {
if (el.value !== null) { if (el.value !== null && !_.isNaN(el.value)) {
averagedScore.value += (el.value * el.days) averagedScore.value += (el.value * el.days)
averagedScore.days += (el.days) averagedScore.days += (el.days)
} else { } else {
console.log('skip averaging') // console.log('skip averaging')
console.log(el) // console.log(el)
} }
}) })