Data not matching when fetching from Google Analytics API (python)





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I'm making a script to pull data from Google Analytics API v4. The script works fine. However, when validating the data by comparing GA with my fetched data I can see some discrepancies. Not too different but I don't understand why is not the same.



Just to mention that I'm using dynamic segments on my script which has the exact same condition as the segment I have in my GA view.
The segment is just filtering spam traffic by only including traffic where session duration > 1sec.



Here is the structure I'm pulling:



body={
"reportRequests":[
{
"viewId": view_id,
"dimensions":[{"name": "ga:date"},{"name": "ga:sourceMedium"},{"name": "ga:campaign"},{"name": "ga:adContent"},{"name": "ga:channelGrouping"},{"name": "ga:segment"}],
"dateRanges":[
{
"startDate":"2018-12-16",
"endDate":"2018-12-20"
}],
"metrics":[{"expression":"ga:sessions","alias":"sessions"}],
"segments":[
{
"dynamicSegment":
{
"name": "sessions_no_spam",
"userSegment":
{
"segmentFilters":[
{
"simpleSegment":
{
"orFiltersForSegment":
{
"segmentFilterClauses": [
{
"metricFilter":
{
"metricName":"ga:sessionDuration",
"operator":"GREATER_THAN",
"comparisonValue":"1"
}
}]
}
}
}]
}
}
}]
}]
}).execute()


Not sure if the answer to my question will be more conceptual rather than technical but just in case I'm also including the function where I bulk the results in my database:



def print_results(no_spam_traffic):
connection = psycopg2.connect(database = 'web_insights_data', user = 'XXXX', password = 'XXXXX', host = 'XXX', port = 'XXXXX')
cursor = connection.cursor()
for report in no_spam_traffic.get('reports', ):
for row in report.get('data', {}).get('rows', ):
gadate = row['dimensions'][0]
gadate = gadate[0:4]+'/'+gadate[4:6]+'/'+gadate[6:8]
gasourcemedium = row['dimensions'][1]
gacampaign = row['dimensions'][2]
gaadcontent = row['dimensions'][3]
gachannel = row['dimensions'][4]
gasessions = row['metrics'][0]['values'][0]

cursor.execute("SELECT * from GA_no_spam_traffic where gadate = %s AND sourcemedium = %s AND campaign = %s AND adcontent = %s", (str(gadate),str(gasourcemedium),str(gacampaign),str(gaadcontent)))
if len(cursor.fetchall())>0: #update old entries
cursor.execute("UPDATE GA_no_spam_traffic set sessions = %s where gadate = %s AND sourcemedium = %s AND campaign = %s AND adcontent = %s", (str(gasessions),str(gadate),str(gasourcemedium),str(gacampaign),str(gaadcontent)))
connection.commit()
else: #Insert new rows
cursor.execute("INSERT INTO GA_no_spam_traffic (gadate,sourcemedium,campaign,adcontent,channel,sessions) VALUES (%s,%s,%s,%s,%s,%s)", (gadate,gasourcemedium,gacampaign,gaadcontent,gachannel,gasessions))
connection.commit()

connection.close()


Any ideas what the issue might be?
Thanks!!










share|improve this question























  • What kind of discrepancies are you seeing between the UI and your API pulls? GA typically uses sampling to quickly display values. Have you tried specifying your sampling level?

    – Dascienz
    Jan 4 at 17:12













  • Yes, if you are seeing small discrepancies I'd look to sampling issues.

    – Sal Cangeloso
    Jan 5 at 3:47











  • Thanks! I shouldn't have sampling issues because I don't have much sessions. With the segment I'm having <90000 during a 35 days period. Just in case I added a parameter to my query: "samplingLevel": "LARGE" but still there is a small discrepancy: 84925 sessions (from my script) vs 86120 (from analytics) The filters I have on my property shouldn't affect, do they? thanks again

    – raul
    Jan 7 at 10:49




















0















I'm making a script to pull data from Google Analytics API v4. The script works fine. However, when validating the data by comparing GA with my fetched data I can see some discrepancies. Not too different but I don't understand why is not the same.



Just to mention that I'm using dynamic segments on my script which has the exact same condition as the segment I have in my GA view.
The segment is just filtering spam traffic by only including traffic where session duration > 1sec.



Here is the structure I'm pulling:



body={
"reportRequests":[
{
"viewId": view_id,
"dimensions":[{"name": "ga:date"},{"name": "ga:sourceMedium"},{"name": "ga:campaign"},{"name": "ga:adContent"},{"name": "ga:channelGrouping"},{"name": "ga:segment"}],
"dateRanges":[
{
"startDate":"2018-12-16",
"endDate":"2018-12-20"
}],
"metrics":[{"expression":"ga:sessions","alias":"sessions"}],
"segments":[
{
"dynamicSegment":
{
"name": "sessions_no_spam",
"userSegment":
{
"segmentFilters":[
{
"simpleSegment":
{
"orFiltersForSegment":
{
"segmentFilterClauses": [
{
"metricFilter":
{
"metricName":"ga:sessionDuration",
"operator":"GREATER_THAN",
"comparisonValue":"1"
}
}]
}
}
}]
}
}
}]
}]
}).execute()


Not sure if the answer to my question will be more conceptual rather than technical but just in case I'm also including the function where I bulk the results in my database:



def print_results(no_spam_traffic):
connection = psycopg2.connect(database = 'web_insights_data', user = 'XXXX', password = 'XXXXX', host = 'XXX', port = 'XXXXX')
cursor = connection.cursor()
for report in no_spam_traffic.get('reports', ):
for row in report.get('data', {}).get('rows', ):
gadate = row['dimensions'][0]
gadate = gadate[0:4]+'/'+gadate[4:6]+'/'+gadate[6:8]
gasourcemedium = row['dimensions'][1]
gacampaign = row['dimensions'][2]
gaadcontent = row['dimensions'][3]
gachannel = row['dimensions'][4]
gasessions = row['metrics'][0]['values'][0]

cursor.execute("SELECT * from GA_no_spam_traffic where gadate = %s AND sourcemedium = %s AND campaign = %s AND adcontent = %s", (str(gadate),str(gasourcemedium),str(gacampaign),str(gaadcontent)))
if len(cursor.fetchall())>0: #update old entries
cursor.execute("UPDATE GA_no_spam_traffic set sessions = %s where gadate = %s AND sourcemedium = %s AND campaign = %s AND adcontent = %s", (str(gasessions),str(gadate),str(gasourcemedium),str(gacampaign),str(gaadcontent)))
connection.commit()
else: #Insert new rows
cursor.execute("INSERT INTO GA_no_spam_traffic (gadate,sourcemedium,campaign,adcontent,channel,sessions) VALUES (%s,%s,%s,%s,%s,%s)", (gadate,gasourcemedium,gacampaign,gaadcontent,gachannel,gasessions))
connection.commit()

connection.close()


Any ideas what the issue might be?
Thanks!!










share|improve this question























  • What kind of discrepancies are you seeing between the UI and your API pulls? GA typically uses sampling to quickly display values. Have you tried specifying your sampling level?

    – Dascienz
    Jan 4 at 17:12













  • Yes, if you are seeing small discrepancies I'd look to sampling issues.

    – Sal Cangeloso
    Jan 5 at 3:47











  • Thanks! I shouldn't have sampling issues because I don't have much sessions. With the segment I'm having <90000 during a 35 days period. Just in case I added a parameter to my query: "samplingLevel": "LARGE" but still there is a small discrepancy: 84925 sessions (from my script) vs 86120 (from analytics) The filters I have on my property shouldn't affect, do they? thanks again

    – raul
    Jan 7 at 10:49
















0












0








0








I'm making a script to pull data from Google Analytics API v4. The script works fine. However, when validating the data by comparing GA with my fetched data I can see some discrepancies. Not too different but I don't understand why is not the same.



Just to mention that I'm using dynamic segments on my script which has the exact same condition as the segment I have in my GA view.
The segment is just filtering spam traffic by only including traffic where session duration > 1sec.



Here is the structure I'm pulling:



body={
"reportRequests":[
{
"viewId": view_id,
"dimensions":[{"name": "ga:date"},{"name": "ga:sourceMedium"},{"name": "ga:campaign"},{"name": "ga:adContent"},{"name": "ga:channelGrouping"},{"name": "ga:segment"}],
"dateRanges":[
{
"startDate":"2018-12-16",
"endDate":"2018-12-20"
}],
"metrics":[{"expression":"ga:sessions","alias":"sessions"}],
"segments":[
{
"dynamicSegment":
{
"name": "sessions_no_spam",
"userSegment":
{
"segmentFilters":[
{
"simpleSegment":
{
"orFiltersForSegment":
{
"segmentFilterClauses": [
{
"metricFilter":
{
"metricName":"ga:sessionDuration",
"operator":"GREATER_THAN",
"comparisonValue":"1"
}
}]
}
}
}]
}
}
}]
}]
}).execute()


Not sure if the answer to my question will be more conceptual rather than technical but just in case I'm also including the function where I bulk the results in my database:



def print_results(no_spam_traffic):
connection = psycopg2.connect(database = 'web_insights_data', user = 'XXXX', password = 'XXXXX', host = 'XXX', port = 'XXXXX')
cursor = connection.cursor()
for report in no_spam_traffic.get('reports', ):
for row in report.get('data', {}).get('rows', ):
gadate = row['dimensions'][0]
gadate = gadate[0:4]+'/'+gadate[4:6]+'/'+gadate[6:8]
gasourcemedium = row['dimensions'][1]
gacampaign = row['dimensions'][2]
gaadcontent = row['dimensions'][3]
gachannel = row['dimensions'][4]
gasessions = row['metrics'][0]['values'][0]

cursor.execute("SELECT * from GA_no_spam_traffic where gadate = %s AND sourcemedium = %s AND campaign = %s AND adcontent = %s", (str(gadate),str(gasourcemedium),str(gacampaign),str(gaadcontent)))
if len(cursor.fetchall())>0: #update old entries
cursor.execute("UPDATE GA_no_spam_traffic set sessions = %s where gadate = %s AND sourcemedium = %s AND campaign = %s AND adcontent = %s", (str(gasessions),str(gadate),str(gasourcemedium),str(gacampaign),str(gaadcontent)))
connection.commit()
else: #Insert new rows
cursor.execute("INSERT INTO GA_no_spam_traffic (gadate,sourcemedium,campaign,adcontent,channel,sessions) VALUES (%s,%s,%s,%s,%s,%s)", (gadate,gasourcemedium,gacampaign,gaadcontent,gachannel,gasessions))
connection.commit()

connection.close()


Any ideas what the issue might be?
Thanks!!










share|improve this question














I'm making a script to pull data from Google Analytics API v4. The script works fine. However, when validating the data by comparing GA with my fetched data I can see some discrepancies. Not too different but I don't understand why is not the same.



Just to mention that I'm using dynamic segments on my script which has the exact same condition as the segment I have in my GA view.
The segment is just filtering spam traffic by only including traffic where session duration > 1sec.



Here is the structure I'm pulling:



body={
"reportRequests":[
{
"viewId": view_id,
"dimensions":[{"name": "ga:date"},{"name": "ga:sourceMedium"},{"name": "ga:campaign"},{"name": "ga:adContent"},{"name": "ga:channelGrouping"},{"name": "ga:segment"}],
"dateRanges":[
{
"startDate":"2018-12-16",
"endDate":"2018-12-20"
}],
"metrics":[{"expression":"ga:sessions","alias":"sessions"}],
"segments":[
{
"dynamicSegment":
{
"name": "sessions_no_spam",
"userSegment":
{
"segmentFilters":[
{
"simpleSegment":
{
"orFiltersForSegment":
{
"segmentFilterClauses": [
{
"metricFilter":
{
"metricName":"ga:sessionDuration",
"operator":"GREATER_THAN",
"comparisonValue":"1"
}
}]
}
}
}]
}
}
}]
}]
}).execute()


Not sure if the answer to my question will be more conceptual rather than technical but just in case I'm also including the function where I bulk the results in my database:



def print_results(no_spam_traffic):
connection = psycopg2.connect(database = 'web_insights_data', user = 'XXXX', password = 'XXXXX', host = 'XXX', port = 'XXXXX')
cursor = connection.cursor()
for report in no_spam_traffic.get('reports', ):
for row in report.get('data', {}).get('rows', ):
gadate = row['dimensions'][0]
gadate = gadate[0:4]+'/'+gadate[4:6]+'/'+gadate[6:8]
gasourcemedium = row['dimensions'][1]
gacampaign = row['dimensions'][2]
gaadcontent = row['dimensions'][3]
gachannel = row['dimensions'][4]
gasessions = row['metrics'][0]['values'][0]

cursor.execute("SELECT * from GA_no_spam_traffic where gadate = %s AND sourcemedium = %s AND campaign = %s AND adcontent = %s", (str(gadate),str(gasourcemedium),str(gacampaign),str(gaadcontent)))
if len(cursor.fetchall())>0: #update old entries
cursor.execute("UPDATE GA_no_spam_traffic set sessions = %s where gadate = %s AND sourcemedium = %s AND campaign = %s AND adcontent = %s", (str(gasessions),str(gadate),str(gasourcemedium),str(gacampaign),str(gaadcontent)))
connection.commit()
else: #Insert new rows
cursor.execute("INSERT INTO GA_no_spam_traffic (gadate,sourcemedium,campaign,adcontent,channel,sessions) VALUES (%s,%s,%s,%s,%s,%s)", (gadate,gasourcemedium,gacampaign,gaadcontent,gachannel,gasessions))
connection.commit()

connection.close()


Any ideas what the issue might be?
Thanks!!







python google-analytics google-analytics-api segment






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 4 at 17:00









raulraul

214




214













  • What kind of discrepancies are you seeing between the UI and your API pulls? GA typically uses sampling to quickly display values. Have you tried specifying your sampling level?

    – Dascienz
    Jan 4 at 17:12













  • Yes, if you are seeing small discrepancies I'd look to sampling issues.

    – Sal Cangeloso
    Jan 5 at 3:47











  • Thanks! I shouldn't have sampling issues because I don't have much sessions. With the segment I'm having <90000 during a 35 days period. Just in case I added a parameter to my query: "samplingLevel": "LARGE" but still there is a small discrepancy: 84925 sessions (from my script) vs 86120 (from analytics) The filters I have on my property shouldn't affect, do they? thanks again

    – raul
    Jan 7 at 10:49





















  • What kind of discrepancies are you seeing between the UI and your API pulls? GA typically uses sampling to quickly display values. Have you tried specifying your sampling level?

    – Dascienz
    Jan 4 at 17:12













  • Yes, if you are seeing small discrepancies I'd look to sampling issues.

    – Sal Cangeloso
    Jan 5 at 3:47











  • Thanks! I shouldn't have sampling issues because I don't have much sessions. With the segment I'm having <90000 during a 35 days period. Just in case I added a parameter to my query: "samplingLevel": "LARGE" but still there is a small discrepancy: 84925 sessions (from my script) vs 86120 (from analytics) The filters I have on my property shouldn't affect, do they? thanks again

    – raul
    Jan 7 at 10:49



















What kind of discrepancies are you seeing between the UI and your API pulls? GA typically uses sampling to quickly display values. Have you tried specifying your sampling level?

– Dascienz
Jan 4 at 17:12







What kind of discrepancies are you seeing between the UI and your API pulls? GA typically uses sampling to quickly display values. Have you tried specifying your sampling level?

– Dascienz
Jan 4 at 17:12















Yes, if you are seeing small discrepancies I'd look to sampling issues.

– Sal Cangeloso
Jan 5 at 3:47





Yes, if you are seeing small discrepancies I'd look to sampling issues.

– Sal Cangeloso
Jan 5 at 3:47













Thanks! I shouldn't have sampling issues because I don't have much sessions. With the segment I'm having <90000 during a 35 days period. Just in case I added a parameter to my query: "samplingLevel": "LARGE" but still there is a small discrepancy: 84925 sessions (from my script) vs 86120 (from analytics) The filters I have on my property shouldn't affect, do they? thanks again

– raul
Jan 7 at 10:49







Thanks! I shouldn't have sampling issues because I don't have much sessions. With the segment I'm having <90000 during a 35 days period. Just in case I added a parameter to my query: "samplingLevel": "LARGE" but still there is a small discrepancy: 84925 sessions (from my script) vs 86120 (from analytics) The filters I have on my property shouldn't affect, do they? thanks again

– raul
Jan 7 at 10:49














1 Answer
1






active

oldest

votes


















0














I managed to improve it, although it's not exact. But well, it's an acceptable discrepancy. I had a problem with the page size so I increased the pagesize parameter.



Here's the link to the pagination section from a google guide: https://developers.google.com/analytics/devguides/reporting/core/v4/migration#pagination
Thanks






share|improve this answer


























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54043183%2fdata-not-matching-when-fetching-from-google-analytics-api-python%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    I managed to improve it, although it's not exact. But well, it's an acceptable discrepancy. I had a problem with the page size so I increased the pagesize parameter.



    Here's the link to the pagination section from a google guide: https://developers.google.com/analytics/devguides/reporting/core/v4/migration#pagination
    Thanks






    share|improve this answer






























      0














      I managed to improve it, although it's not exact. But well, it's an acceptable discrepancy. I had a problem with the page size so I increased the pagesize parameter.



      Here's the link to the pagination section from a google guide: https://developers.google.com/analytics/devguides/reporting/core/v4/migration#pagination
      Thanks






      share|improve this answer




























        0












        0








        0







        I managed to improve it, although it's not exact. But well, it's an acceptable discrepancy. I had a problem with the page size so I increased the pagesize parameter.



        Here's the link to the pagination section from a google guide: https://developers.google.com/analytics/devguides/reporting/core/v4/migration#pagination
        Thanks






        share|improve this answer















        I managed to improve it, although it's not exact. But well, it's an acceptable discrepancy. I had a problem with the page size so I increased the pagesize parameter.



        Here's the link to the pagination section from a google guide: https://developers.google.com/analytics/devguides/reporting/core/v4/migration#pagination
        Thanks







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jan 8 at 16:56

























        answered Jan 7 at 13:36









        raulraul

        214




        214
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54043183%2fdata-not-matching-when-fetching-from-google-analytics-api-python%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Monofisismo

            Angular Downloading a file using contenturl with Basic Authentication

            Olmecas